Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string into multiple primitive types

Tags:

c++

string

split

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

like image 809
Jaimie Knox Avatar asked Sep 23 '26 19:09

Jaimie Knox


1 Answers

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;
}
like image 72
Potatoswatter Avatar answered Sep 26 '26 09:09

Potatoswatter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!