c++ - 拆分一串制表符分隔的整数并将它们存储在 vector 中

标签 c++ string fstream ifstream

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/

相关文章:

c++ - 通过 C 中的链表实现的堆栈

c++将类的实例转换为另一个

c++ - C++ 中的 fstream 数组

c++ - 我可以使用使用调试符号重新编译的相同二进制文件来调试由没有调试符号的 C++ 二进制文件生成的内核吗

c++ - 如何在 C++ 中使用枚举作为标志?

string - 处理字符串问题

java - String.split 与 ** 崩溃

c++ - Embarcadero 无法从 'UnicodeString' 转换到 'unsigned char *'

c++ - 具有弹出功能的 istream

c++ - 如何将包含另一个对象 vector 的对象保存到文件中,并使用C++中的二进制文件从文件中读取?