在C ++中将字符串拆分为多个变量 [英] Splitting a string into multiple variables in C++

查看:222
本文介绍了在C ++中将字符串拆分为多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个程序,从用户读取一个字符串,并使用它来处理请求。发出提示后,我可以通过以下形式的三种回复中的一种:

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. 字符串

  2. 字符串整数

  3. 字符串

根据用户给出的命令类型,程序是做不同的任务。我有一个困难的时间试图处理用户输入。要清楚,用户将键入命令作为单个字符串,因此,用户行使选项二的示例可能在提示后输入age 8。在这个例子中,我希望程序将age存储为字符串,将8作为整数存储。

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?

根据我在这里收集到的内容,使用strtok()或boost可能是一个解决方案。我试过两个没有成功,但它将是非常有益的,如果有人可以帮助使事情更清楚。提前感谢

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

推荐答案

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

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;
}

这篇关于在C ++中将字符串拆分为多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆