【问题标题】:C++ read pipe delimited fileC ++读取管道分隔文件
【发布时间】:2020-08-14 02:04:41
【问题描述】:

我有包含此信息的 file1.txt

4231650|A|4444
4225642|A|5555

我在这里查看了如何在 C++ 中读取管道分隔文件的代码

C++ Read file line by line then split each line using the delimiter

我根据需要稍微修改了代码。问题是它可以很好地读取第一个管道,但之后我如何读取其余的值?

这是我的代码:

std::ifstream file("file1.txt");
    std::string   line;

    while(std::getline(file, line))
    {
        std::stringstream   linestream(line);
        std::string         data;
        std::string         valStr1;
        std::string         valStr2;


        std::getline(linestream, data, '|');  // read up-to the first pipe

        // Read rest of the pipe values? Why did the accepted answer worked for int but not string???
        linestream >> valStr1 >> valStr2;

        cout << "data: " <<  data << endl;
        cout << "valStr1: " <<  valStr1 << endl;
        cout << "valStr2: " <<  valStr2 << endl;
    }

这是输出:

Code Logic starts here ...
data: 4231650
valStr1: A|4444
valStr2: A|4444
data: 4225642
valStr1: A|5555
valStr2: A|5555
Existing ...

【问题讨论】:

  • 您没有代码可以读取到第二个管道!您也不会检查您的读取是否成功。
  • @DavidSchwartz 我复制并粘贴了上一篇文章中接受的答案。并将其用于字符串而不是 int
  • @SamB 切勿将他人的代码剪切/粘贴到您的代码中,除非您理解并亲自确认它适用于您的问题。
  • 这不是“它与 int 合作”。它是“它与制表符(空格)分隔的值一起使用”。

标签: c++ readfile


【解决方案1】:

为什么接受的答案适用于 int 而不是 string?

因为| 不是数字,而是 int 数字的隐式分隔符。但它是字符串的好字符。

以同样的方式继续这样做

std::getline(linestream, data, '|');
std::getline(linestream, varStr1, '|');
std::getline(linestream, varStr2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2020-07-21
    • 2014-12-15
    • 2016-02-06
    • 2020-06-23
    相关资源
    最近更新 更多