[英]c++ read from stdin store in vector and stdout
我正在測試此代碼,該代碼讀取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]#
在for
循環的初始化部分,您聲明一個新變量vsi
其類型為int
。
解決問題的一種方法:
vsi = vs.begin();
for (int count=1; vsi != vs.end(); ...
問題在這條線上:
for (int count=1 , vsi = vs.begin(); vsi != vs.end(); vsi++,count++)
您定義了兩個int
變量: count
和vsi
。 然后,嘗試使用vs.begin()
分配第二個。 這就是編譯器所抱怨的。
問題在於vs.begin()不返回int,並且您將vsi聲明為整數。
輕松解決:
for (int count=0;count < vs.size(); ++count){
cout << "string" << (count+1) <<"="<< vs[count] << endl;
}
筆記:
更喜歡++count
來count++
盡管在這種情況下沒有區別,但在某些情況下確實有區別。
因此,這是一個好習慣。
請參閱: ++ iterator和Iterator ++之間的性能差異?
while (!(cin.eof()))
實際上總是錯誤的(在所有語言中)。
直到您讀完eof之后,“ eof標志”才設置為true。
最后一次成功的讀取最多讀取(但不超過)eof。 因此,您最后一次進入循環,讀取將失敗,但是您仍然將值推回向量中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.