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 ...
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);