如何将多个输入存储到列表C++中

How to store multiple inputs into a list C++

本文关键字:列表 C++ 存储 输入      更新时间:2023-10-16

我是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",中间有一个空格,但每当我输入空格时,程序都不会按照我希望的方式运行,也不会问用户两次。

来自cin的

输入是包含空格的白色空间。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);

同时,它将使您能够输入任意数量的多个输入。

点击此处查看更多信息。