0

So i'm doing a program where i input some data into a file and read from it. The problem is i dont know how to handle this. I read from the file and recieve a string containing alot of different data that is seperated by a delimiter "|".

   string data ="FirstName|LastName|Signature|Height";

So my question is, is there a way to seperate this string nicely and store each of the values in a seperate variable?

p.s I have tried this so far. I did find this function subrt() and find() which i could use in order to find the delimiter and take out a value but it doesnt give the correct value for me so i think i'm doing something wrong with it. Only the fname value is correct.

    const string DELIM = "|";
    string fname = data.substr(0, data.find(DELIM));
    string lname = data.substr(1, data.find(DELIM));
    string signature = data.substr(2, data.find(DELIM));
    string height = data.substr(3, data.find(DELIM));
user3611818
  • 247
  • 2
  • 3
  • 13

1 Answers1

1

You did not understand how substr() works. The first parameter is not the number of character found, it is the index at which to start. See the doc. You should do the same for the find function. Something like that:

string const DELIM = "|";
auto const firstDelim = data.find(DELIM);
auto const secondDelim = data.find(DELIM, firstDelim + 1); // begin after the first delim
// and so on

auto fname = data.substr(0, firstDelim);
auto lname = data.substr(firstDelim + 1, secondDelim);
// and so on
Adrien Hamelin
  • 395
  • 3
  • 9