[英]c++ read from stdin store in vector and stdout
i am testing out this code which reads stdin and stores it in vector and stdout..any idea what the problem could be?? 我正在测试此代码,该代码读取stdin并将其存储在vector和stdout ..任何想法中可能是什么问题?
#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 variable vsi
whose type is int
. 在
for
循环的初始化部分,您声明一个新变量vsi
其类型为int
。
One way to fix the problem: 解决问题的一种方法:
vsi = vs.begin();
for (int count=1; vsi != vs.end(); ...
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
. 您定义了两个
int
变量: count
和vsi
。 Then, you try to assign the second with vs.begin()
. 然后,尝试使用
vs.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. 问题在于vs.begin()不返回int,并且您将vsi声明为整数。
Easy fix: 轻松解决:
for (int count=0;count < vs.size(); ++count){
cout << "string" << (count+1) <<"="<< vs[count] << endl;
}
Notes: 笔记:
prefer ++count
to count++
更喜欢
++count
来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++? 请参阅: ++ iterator和Iterator ++之间的性能差异?
while (!(cin.eof()))
is practically always wrong (in all languages). while (!(cin.eof()))
实际上总是错误的(在所有语言中)。
The 'eof flag' is not set to true until after you read past the eof. 直到您读完eof之后,“ eof标志”才设置为true。
The last successful read reads up-to (but not past) the eof. 最后一次成功的读取最多读取(但不超过)eof。 So you enter the loop a final time and the read will fail yet you still push back a value into the vector.
因此,您最后一次进入循环,读取将失败,但是您仍然将值推回向量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.