gpt4 book ai didi

c++ - 如何将 vector 转换为字符串并转换回 vector

转载 作者:行者123 更新时间:2023-11-28 03:11:36 29 4
gpt4 key购买 nike

---------------- 编辑------------------------

根据 juanchopanza 的评论:我编辑标题

根据 jrok 的评论:我正在使用 ofstream 进行写入,使用 ifstream 进行读取。

我正在编写 2 个程序,第一个程序执行以下任务:

  1. 有一个整数 vector
  2. 将其转化为字符串数组
  3. 写在文件里

第一个程序的代码:

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 .....

第二个程序将完成以下任务:

  1. 阅读文件
  2. 将字符串数组转换回原始 vector

---------------- 编辑------------------------

现在写作和阅读都很好,感谢 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com