3

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:

  1. string string
  2. string integer
  3. string

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

Jaimie Knox
  • 167
  • 2
  • 4
  • 13
  • 2
    something like `string str; int num; cin >> str >> num;` doesn't work for you? – Shahbaz Apr 17 '12 at 15:18
  • I suppose the only problem would be how to determine if the user gave input in the form of string string, or string, instead of string integer as in the example. – Jaimie Knox Apr 17 '12 at 15:25
  • @Shahbaz: That won't work in case 3. You'd want to read a line, then parse that, perhaps from a `stringstream`. – Mike Seymour Apr 17 '12 at 15:25
  • @MikeSeymour, sorry I understood that the user first gives his choice, then enters one of the three forms. – Shahbaz Apr 17 '12 at 16:07

1 Answers1

6

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;
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421