我正在写 2 个程序,第一个程序有一个整数数组
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
我做错了什么?谢谢