我正在编写两个程序,第一个程序有一个整数数组。
vector<int> v = {10, 200, 3000, 40000};
那么它会将向量转换为字符串。
int i;
stringstream sw;
string stringword;
for (i=0;i<v.size();i++)
{
sw << v[i] << ',';
}
stringword = sw.str();
cout << "Vector in string : "<< stringword << endl;
然后将其写入文件中。
ofstream myfile;
myfile.open ("writtentext");
myfile << stringword;
myfile.close();
输出结果:
Vector in string : 10,200,3000,40000
第二个程序将读取文件,将字符串转换回整数,然后将其推回到向量中。
代码如下:
string stringword;
ifstream myfile;
myfile.open ("writtentext");
getline (myfile,stringword);
cout << "Read From File = " << stringword << endl;
cout << "Convert back to vector = " ;
for (int i=0;i<stringword.length();i++)
{
if (stringword.find(','))
{
int value;
istringstream (stringword) >> value;
v.push_back(value);
stringword.erase(0, stringword.find(','));
}
}
for (int j=0;j<v.size();j++)
{
cout << v.at(j) << " " ;
}
问题在于它只能转换并推回第一个元素,其余部分都被删除了。以下是输出结果:
Read From File = 10,200,3000,40000,
Convert back to vector = 10
我做错了什么?谢谢。
stringword.find(',')
返回的内容(http://en.cppreference.com/w/cpp/string/basic_string/find)。如果这不明显,请通过调试器运行代码,您会看到结果。在此过程中,同时查看`erase`的文档:http://en.cppreference.com/w/cpp/string/basic_string/erase。 - R. Martinho Fernandes