将字符串拆分为多个基本类型

时间:2012-04-17 15:16:47

标签: c++ string split

我正在编写一个程序,该程序从用户读取字符串并使用它来处理请求。发出提示后,我可以期待以下两种形式之一的三种可能的回答之一:

  1. 字符串字符串
  2. 字符串整数
  3. 字符串
  4. 根据用户提供的命令类型,程序将执行不同的任务。我正在努力处理用户输入。要清楚,用户将键入命令作为单个字符串,因此执行选项二的用户的示例可能在提示后输入“年龄8”。在这个例子中,我希望程序将“age”存储为字符串,将“8”存储为整数。这会是一个好方法吗?

    从我在这里收集到的,使用strtok()或boost可能是一个解决方案。我已经尝试过两次都没有成功,如果有人可以帮助让事情更清楚,那将会非常有帮助。提前致谢

1 个答案:

答案 0 :(得分:6)

在使用std::getline获得一行输入后,您可以使用std::istringstream来回收文本以进行进一步处理。

// 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;
}
相关问题