如何将多个输入存储到列表C++中
How to store multiple inputs into a list C++
我是C++编程的新手,正在尝试创建一个向用户提问的程序。例如,
std::string siblings;
std::cout << "How many siblings do you have?"; //Let's say the user inputs 2
std::cin >> siblings;
for (int x=0;x<n;x++){
std::string current;
std::string sibling_info;
std::cout << "What is the name + age of sibling #" << (x+1) << ": ";
std::cin >> current;
sibling_info.emplace_back(current);
我希望用户输入"John 13",中间有一个空格,但每当我输入空格时,程序都不会按照我希望的方式运行,也不会问用户两次。
输入是包含空格的白色空间。CCD_ 1仅存储键入的第一个单词。为了获得两个单词,您必须调用cin两次,或者切换到不同的获取用户输入的方式。
std::string current;
std::string age;
std::string sibling_info;
std::cout << "What is the name + age of sibling #" << (x+1) << ": ";
std::cin >> current; //you were missing a semicolon :p
std::cin >> age; //added
current += " " + age; //added
sibling_info.emplace_back(current);
或使用getline(您需要#include<string>
)
std::string current;
std::string sibling_info;
std::cout << "What is the name + age of sibling #" << (x+1) << ": ";
current = getline(cin,current); //changed
sibling_info.emplace_back(current);
一种方法:
std::string current[2];
...
std::cin >> current[0] >> current[1];
sibling_info.emplace_back(current[0]+" "+current[1]);
emplace_back()
可用于vector
,但不能用于string
。所以你需要改变
std::string sibling_info;
至
std::vector<std::string> sibling_info;
然后您可以拨打:
sibling_info.emplace_back(current);
同时,它将使您能够输入任意数量的多个输入。
点击此处查看更多信息。
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 没有为自己的结构调用列表推回方法
- 使用简单类型列表实现的指数编译时间.为什么
- 一对向量构造函数:初始值设定项列表与显式构造
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 通过for循环使用用户输入填充列表
- C++:如何使函数只返回作为列表一部分的字符串
- 概念中的cv限定符需要表达式参数列表
- 下面是我为检测链接列表中的循环而制作的代码
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在卡萨布兰卡形成编码参数的列表
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题