C ++读取管道分隔文件

C++ read pipe delimited file

我 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 ...

Why did the accepted answer worked for int but not string?

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

以同样的方式继续

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