首页 > 解决方案 > 拆分一串制表符分隔的整数并将它们存储在向量中

问题描述

ifstream infile;
infile.open("graph.txt");
string line;
while (getline(infile, line))
{
       //TODO
}
infile.close();

我从文件中逐行获取输入并将每一行存储在字符串“line”中。

每行包含由制表符分隔的整数。我想将这些整数分开并将每个整数存储在一个向量中。但我不知道如何进行。splitC++ 中是否有类似字符串的函数?

标签: c++stringfstreamifstream

解决方案


副本有一些解决方案,但是,我更喜欢使用 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可以接受范围的整数将不会被解析并会触发仅该行的流错误状态,继续在下一行解析。


推荐阅读