【问题标题】:Delimiter extracting out a range of data分隔符提取出一系列数据
【发布时间】:2013-08-12 09:48:30
【问题描述】:

来自文本文件(Range.txt),

Range:1:2:3:4:5:6....:n:

有一个结果列表,但我只需要提取数字 1 2 3 到最后一位,但有时最后一位可能会有所不同

所以我读入文件,提取分隔符并将其推入向量中。

ifstream myfile;
myfile.open("Range.txt");

istringstream range(temp);
getline(range, line,':');

test.push_back(line);

如何获取所有价值?我有这个,它只捕获一个数字。

【问题讨论】:

  • 这可以通过Boost.Split 或您自己的拆分函数来完成。

标签: c++ delimiter getline


【解决方案1】:

我有这个,它只捕获一个数字

你需要使用循环:-

while (getline(range, line, ':')) 
  test.push_back(line);

稍后您可以使用向量对其进行处理以仅获取整数。

【讨论】:

    【解决方案2】:

    请阅读:Parsing and adding string to vector

    您只需更改分隔符(从 whitespace:)。

    std::ifstream infile(filename.c_str());
    std::string line;
    
    if (infile.is_open())
    {
        std::cout << "Well done! File opened successfully." << std::endl;
        while (std::getline(infile, line, ':'))
        {
            std::istringstream iss(line);
            std::vector<std::string> tokens{std::istream_iterator<std::string>(iss),std::istream_iterator<std::string>()};
    
            // Now, tokens vector stores all data.
            // There is an item for each value read from the current line.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多