Splitting a string into several primitive types

I am writing a program that reads a string from a user and uses it to process a request. After giving a hint, I can expect one of three possible answers in the form:

  • Line
  • string integer
  • line

Depending on what type of command the user gives, the program must perform another task. I have a hard time trying to handle user input. To be clear, the user enters the command as one line, so the example of the user executing the second option may enter "age 8" after the request. In this example, I would like the program to save "age" as a string and "8" as an integer. What would be a good way to get around this?

From what I have compiled here, using strtok () or boost may be the solution. I tried both without success, and it would be very helpful if someone helped make everything clearer. thanks in advance

+3
source share
1 answer

After receiving one line of input with, std::getlineyou can use std::istringstreamto process the text for further processing.

// get exactly one line of input
std::string input_line;
getline( std::cin, input_line );

// go back and see what input was
std::istringstream parse_input( input_line );

std::string op_token;
parse_input >> op_token;

if ( op_token == "age" ) {
    // conditionally extract and handle the individual pieces
    int age;
    parse_input >> age;
}
+6
source

All Articles