C++ c++;从存储在向量和标准输出中的标准输入读取
我正在测试这段代码,它读取stdin并将其存储在vector和stdout中。知道问题出在哪里吗C++ c++;从存储在向量和标准输出中的标准输入读取,c++,linux,C++,Linux,我正在测试这段代码,它读取stdin并将其存储在vector和stdout中。知道问题出在哪里吗 #include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<string> vs; vector<string>::iterator vsi; string buffer; while
#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]#
#包括
#包括
#包括
使用名称空间std;
int main(){
向量vs;
向量::迭代器vsi;
字符串缓冲区;
而(!(cin.eof()){
getline(cin,buffer);
cout在for
循环的初始化部分,声明一个新变量vsi
,其类型为int
解决此问题的一种方法:
vsi = vs.begin();
for (int count=1; vsi != vs.end(); ...
在for
循环的初始化部分,声明一个类型为int
的新变量vsi
解决此问题的一种方法:
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()
分配第二个变量。这就是编译器抱怨的问题。问题在这一行:
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;
}
for(int count=0;count cout问题在于vs.begin()不返回int,并且您将vsi声明为整数
简易修复:
for (int count=0;count < vs.size(); ++count){
cout << "string" << (count+1) <<"="<< vs[count] << endl;
}
for(int count=0;count cout Note:whilewhile
循环从根本上被打破了。永远不要做while(!(cin.eof()){
(你可以找到很多关于它的文章,所以可以搜索一下。你应该做while(getline(cin,buffer)){
快速搜索:注意:while
循环从根本上被打破了。永远不要做while(!(cin.eof()){
(你可以找到许多关于它的文章,因此可以进行搜索。你应该在(getline(cin,buffer))时执行{
快速搜索: