0

I have file1.txt with this information

4231650|A|4444
4225642|A|5555

I checked the code here for how to read pipe delimited file in C++

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

I modified the code a little bit per my needs. The problem is that it reads the first pipe fine but afterwards how do I read rest of the values?

This is my code:

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;
    }

Here's the output:

Code Logic starts here ...
data: 4231650
valStr1: A|4444
valStr2: A|4444
data: 4225642
valStr1: A|5555
valStr2: A|5555
Existing ...
Sam B
  • 27,273
  • 15
  • 84
  • 121
  • See also [splitting a string in C++](https://stackoverflow.com/questions/275404/splitting-strings-in-c). – tadman Apr 29 '20 at 20:25
  • You have no code to read up to the second pipe! You also don't check if your reads succeed. – David Schwartz Apr 29 '20 at 20:32
  • @DavidSchwartz I copied and pasted the accepted answer from previous post. and tweeked it a bit for strings instead of int – Sam B Apr 29 '20 at 20:34
  • @SamB Never cut/paste someone else's code into yours unless you understand it and have personally confirmed that it applies as-is to your problem. – David Schwartz Apr 29 '20 at 20:35
  • It's not "it worked with `int`". It's "it worked with tab (whitespace) delimited values". – Yksisarvinen Apr 29 '20 at 20:35

1 Answers1

2

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

Because | is not a digit and is an implicit delimiter for int numbers. But it is a good char for a string.

Continue doing it in the same way

std::getline(linestream, data, '|');
std::getline(linestream, varStr1, '|');
std::getline(linestream, varStr2);
273K
  • 29,503
  • 10
  • 41
  • 64