Home > Back-end >  Reading integer then rest of the line as a single string from input
Reading integer then rest of the line as a single string from input

Time:11-10

Suppose I'm trying to read from the following input.txt

6 Jonathan Kim Jr
2 Suzie McDonalds
4 Patty

... and I want to store the first integers from every line and the rest of the strings as a string variable. This is what I have tried:

int num;
string name1, name2, name3;   
while ( ins >> num >> name1 >> name2 >> name3 )
{  
    // do things
}

Unfortunately this won't work since line 2 and line 3 only has 2 and 1 strings in a respective order so the loop will terminate at the very first loop.

Is there a way to store the rest of the strings after an integer in a single variable, including the white spaces? For example, string variable name would hold:

"Jonathan Kim Jr" // first loop
"Suzie M"         // second loop
"Patty"           // third loop

I thought about using getline to achieve this as well, but that would require me to isolate the integers from the string and I was hoping there's a better approach do this. Perhaps using a vector?

CodePudding user response:

By default, the >> operator splits on a space, so you could use that to pull the integer into the variable. You could then use getline to grab the rest of the line, and store that into the variable.

Example (if you are reading from std::cin):

int num;
std::string name;
std::cin >> num;
std::getline(std::cin, name);

CodePudding user response:

Why don't use regular expressions (https://en.wikipedia.org/wiki/Regular_expression) to parse (https://en.cppreference.com/w/cpp/regex) the input? I think an expression something along the line of 2 subexpressions:

'^([0-1] )\s([A-Za-z0-9_-/s] )'

  • Related