C++ 容器vector 问题

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

using namespace std;

int main()
{
vector<string> svec;
string str;

while (str != NULL)
{
cin >> str;
svec.push_back(str);
}
cout << str[0];
cout << str[1];
cout << str[2];

return 0;
}

svec.cpp
C:\Work\svec\svec.cpp(12) : error C2676: binary '!=' : 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' does not define this operator or a conversion to a type acceptable to the predefined operator
C:\Work\svec\svec.cpp(12) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.
错误的原因是什么? 怎么改?

你的cout其实是想输出向量的内容,而不是字符串吧,帮你修改于完善了一下,你读一下程序。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
vector<string> svec;
string str;
do
{ cout<<"请输入字符串,输入$结束"<<endl;
cin >> str;
svec.push_back(str);
}while (str!="$");
for(int i=0;i<svec.size();i++)
cout<<svec[i]<<endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-26

str不是指针,只有指针才能使用!=NULL,可参考改为如下(ctrl+z结束):

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

using namespace std;

int main()
{
vector<string> svec;
string str;

while (cin >> str)
{
svec.push_back(str);
}
cout << str[0];
cout << str[1];
cout << str[2];

return 0;
}

第2个回答  2013-08-26
while (str != NULL)//str是string类型,将其与NULL比较想得到什么结果?
//如果想判断str是否包含字符的话大概需要的是
str.size()!=0 /* 或 */ str!=""

相似回答