ifstream infile;
infile.open("graph.txt");
string line;
while (getline(infile, line))
{
//TODO
}
infile.close();
我从文件中逐行获取输入并将每一行存储在字符串“line”中。
每行包含由制表符分隔的整数。我想将这些整数分开并将每个整数存储在 vector 内。但我不知道如何继续。 C++ 中有类似 split
字符串函数的东西吗?
最佳答案
拷贝有一些解决方案,但是,我更喜欢使用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 stated这会将文件中的所有 int
值存储在 vector v
中,假设文件实际上只有 int
值,例如,超出 int
可接受范围的字母字符或整数将不会被解析,并且只会触发该行的流错误状态,并在下一行中继续解析。
关于c++ - 拆分一串制表符分隔的整数并将它们存储在 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66987040/