作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
---------------- 编辑------------------------
根据 juanchopanza 的评论:我编辑标题
根据 jrok 的评论:我正在使用 ofstream 进行写入,使用 ifstream 进行读取。
我正在编写 2 个程序,第一个程序执行以下任务:
第一个程序的代码:
vector<int> v = {10, 200, 3000, 40000};
int i;
stringstream sw;
string stringword;
cout << "Original vector = ";
for (i=0;i<v.size();i++)
{
cout << v.at(i) << " " ;
}
cout << endl;
for (i=0;i<v.size();i++)
{
sw << v[i];
}
stringword = sw.str();
cout << "Vector in array of string : "<< stringword << endl;
ofstream myfile;
myfile.open ("writtentext");
myfile << stringword;
myfile.close();
第一个程序的输出:
Original vector : 10 200 3000 40000
Vector in string : 10200300040000
Writing to File .....
第二个程序将完成以下任务:
---------------- 编辑------------------------
现在写作和阅读都很好,感谢 Shark 和 Jrok,我使用逗号作为分隔符。第一个程序的输出:
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();i++)
{
cout << v.at(i) << " " ;
}
但它只能转换并推回第一个元素,其余的被删除。这是输出:
Read From File = 10,200,3000,40000,
Convert back to vector = 10
我做错了什么?谢谢
最佳答案
最简单的方法是在编写时插入一个空格字符作为分隔符,因为这是 operator>> 的默认分隔符
sw << v[i] << ' ';
现在您可以直接读回int
变量,格式化流输入会自动为您进行转换。使用 vector 的 push_back
方法随时为其添加值。
关于c++ - 如何将 vector 转换为字符串并转换回 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18314581/
我是一名优秀的程序员,十分优秀!