c++ read from stdin store in vector and stdout

2019-09-07 06:10发布

i am testing out this code which reads stdin and stores it in vector and stdout..any idea what the problem could be??

#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main() {
  vector<string> vs;
  vector<string>::iterator vsi;

  string buffer;
  while (!(cin.eof())) {
    getline(cin, buffer);
    cout << buffer << endl;
    vs.push_back(buffer);
  };

  for (int count=1 , vsi = vs.begin(); vsi != vs.end(); vsi++,count++){
    cout << "string" << count <<"="<< *vsi << endl;
  }

  return 0;
}



[root@server dev]# g++ -o newcode newcode.cpp 
newcode.cpp: In function ‘int main()’:
newcode.cpp:19: error: cannot convert ‘__gnu_cxx::__normal_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >*, std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >’ to ‘int’ in initialization
newcode.cpp:19: error: no match for ‘operator!=’ in ‘vsi != vs.std::vector<_Tp, _Alloc>::end [with _Tp = std::basic_string<char, std::char_traits<char>, std::allocator<char> >, _Alloc = std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >]()’
newcode.cpp:20: error: invalid type argument of ‘unary *’
[root@server dev]# 

标签: c++ linux
3条回答
孤傲高冷的网名
2楼-- · 2019-09-07 06:22

In the initialization part of the for loop, you declare a new variable vsi whose type is int.

One way to fix the problem:

vsi = vs.begin();
for (int count=1; vsi != vs.end(); ...
查看更多
Fickle 薄情
3楼-- · 2019-09-07 06:22

Problem is on this line:

for (int count=1 , vsi = vs.begin(); vsi != vs.end(); vsi++,count++)

You define two int variables: count and vsi. Then, you try to assign the second with vs.begin(). This is what the compiler complains about.

查看更多
再贱就再见
4楼-- · 2019-09-07 06:39

The problem is that vs.begin() does not return an int, and you declared vsi as an integer.

Easy fix:

for (int count=0;count < vs.size(); ++count){
  cout << "string" << (count+1) <<"="<< vs[count] << endl;
}

Notes:

  • prefer ++count to count++
    Though it makes not difference in this case there are situations where it does.
    So it is a good habit to get into.
    See: Performance difference between ++iterator and iterator++?

  • while (!(cin.eof())) is practically always wrong (in all languages).
    The 'eof flag' is not set to true until after you read past the eof.
    The last successful read reads up-to (but not past) the eof. So you enter the loop a final time and the read will fail yet you still push back a value into the vector.

    • In Some situations this can cause an infinite loop.
      If there is another type of failure on read you will never reach the eof
      (eg cin >> x; Where x is an int may fail if input is not an integer)
      See: c++ reading undefined number of lines with eof()
查看更多
登录 后发表回答