Reputation: 166
I'm writing a program that reads a string from the user and uses it to process a request. After issuing a prompt, I can expect one of three possible responses in the form of either:
Depending on which type of command the user gives, the program is to do a different task. I'm having a difficult time trying to process the users input. To be clear, the user will type the command as a single string, so an example of a user exercising option two might input "age 8" after the prompt. In this example I would like the program to store "age" as a string and '8' as an integer. What would be a good way of going about this?
From what I've gathered on here, using strtok() or boost might be a solution. I've tried both without success however and it would be very helpful if someone could help make things clearer. Thanks in advance
Upvotes: 3
Views: 3205
Reputation: 137810
After getting one line of input with std::getline
, you can use a std::istringstream
to recycle 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;
}
Upvotes: 6