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]#
In the initialization part of the
for
loop, you declare a new variablevsi
whose type isint
.One way to fix the problem:
Problem is on this line:
You define two
int
variables:count
andvsi
. Then, you try to assign the second withvs.begin()
. This is what the compiler complains about.The problem is that vs.begin() does not return an int, and you declared vsi as an integer.
Easy fix:
Notes:
prefer
++count
tocount++
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.
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()