c++ - 拆分一串制表符分隔的整数并将它们存储在向量中
问题描述
ifstream infile;
infile.open("graph.txt");
string line;
while (getline(infile, line))
{
//TODO
}
infile.close();
我从文件中逐行获取输入并将每一行存储在字符串“line”中。
每行包含由制表符分隔的整数。我想将这些整数分开并将每个整数存储在一个向量中。但我不知道如何进行。split
C++ 中是否有类似字符串的函数?
解决方案
副本有一些解决方案,但是,我更喜欢使用 a stringstream
,例如:
#include <sstream>
//...
vector<int> v;
if (infile.is_open()) // make sure the file opening was successful
{
while (getline(infile, line))
{
int temp;
stringstream ss(line); // convert string into a stream
while (ss >> temp) // convert each word on the stream into an int
{
v.push_back(temp); // store it in the vector
}
}
}
正如Ted Lyngmo 所说 ,这会将int
文件中的所有值存储在 vectorv
中,假设文件实际上只有int
值,例如字母字符或超出 anint
可以接受范围的整数将不会被解析并会触发仅该行的流错误状态,继续在下一行解析。
推荐阅读
- javascript - 如何将员工验证与 javascript 集成
- reactjs - × TypeError: Cannot read property 'props' of undefined 但我正在使用箭头函数,我尝试使用 bind(this) 但它并没有消失
- javascript - 这个地方的+是什么意思?
- ios - 一行上两个标签的字体大小
- flutter - Flutter:如何将数据添加到列表中?
- c# - 我正在使用带有复选框的隐藏 for 将字符串发送到属性,但即使未选中复选框也会发送它们
- javascript - 在这种情况下如何在 TypeScript 中的类型、类、函数类型之间进行选择?
- javascript - 使用 jQuery.each() 方法显示隐藏元素
- selenium - 如何使用 Selenium 和 Python 在 iframe 中单击元素
- flutter - Flutter 如何在使用 sqflite 的应用程序启动时填充 ListView?