【问题标题】:Split a string of tab separated integers and store them in a vector拆分一串制表符分隔的整数并将它们存储在向量中
【发布时间】:2021-04-07 13:25:23
【问题描述】:
ifstream infile;
infile.open("graph.txt");
string line;
while (getline(infile, line))
{
       //TODO
}
infile.close();

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

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

【问题讨论】:

标签: c++ string fstream ifstream


【解决方案1】:

副本有一些解决方案,但是我更喜欢使用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值存储在向量v中,假设文件实际上只有int值,例如字母字符或超出范围的整数int 可以接受的内容不会被解析,只会触发该行的流错误状态,并在下一行继续解析。

【讨论】:

  • 我正在考虑如何更好地表述最后一句话,因为如果遇到像1 2 FOO 3 4 这样的行,它不会存储 all 整数。
  • @TedLyngmo,这是真的,我假设文件 olny 有整数。
  • @anastaciu 是的,它只有整数,谢谢
猜你喜欢
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 2021-10-18
  • 2010-12-26
  • 2015-10-21
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多