简体   繁体   English

如何按空间在C ++中存储多个输入

[英]How to store multiple inputs in C++ by space

I am new to C++ and I want the user to input a set of data followed by spaces like this: 我是C ++的新手,我希望用户输入一组数据,后跟这样的空格:

Mark 23 California, USA
Susan 22 Tokyo, Japan
Anna 21 New Mexico, USA

I am not sure how to gather all of these separate information. 我不确定如何收集所有这些单独的信​​息。 I want to categorize them by name, age, location so I can access them later on by using (age[0]. age[1], etc) 我想按名称,年龄,位置对其进行分类,以便以后可以使用(age [0]。age [1]等)进行访问。

So far, this is what I have 到目前为止,这就是我所拥有的

std::vector<std::string> name, age, location:
std::cout << "Hello, what is your Name Age Location? (separate by space) ";
std::string a, b, c;
std::cin >> a;
std::cin >> b;
std::cin >> c;
a.push_back(name);
b.push_back(age);
c.push_back(location);

std::cout << "How many people would you like to store their data? ";
int n;
std::cin >> n;

for (int a=0;a<n;a++){
    std::cout << "Please enter the Name Age Location for Person #" << n << ": ";
    std::string x, y, z;
    std::cin >> x;
    std::cin >> y;
    std::cin >> z; //this part always gets me because the location is separated by a space and always gets cut off
    x.push_back(name);
    y.push_back(age);
    z.push_back(location);
}

I want to know how to be able to store the rest of the information after the 2nd white space until the end of the line. 我想知道如何能够在第二个空格之后直到行尾存储其余信息。 Thank you!! 谢谢!!

You read the name and age values as you're doing, but then use std::getline to get the rest of the line, ie the location. 您在执行操作时会读取名称和年龄值,然后使用std::getline获取该行的其余部分,即位置。

std::cin >> name;
std::cin >> age;
std::getline(std::cin, location); // voila!

std::cin will break the line in general after a space, use std::getline() instead: std :: cin通常会在空格后换行,请使用std :: getline()代替:

char buffer[256];
std::getline(buffer, size(buffer));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM