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

时间:2014-01-20 20:06:00

标签: c++

我是C ++的新手,我希望用户输入一组数据,然后输入如下空格:

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

我不确定如何收集所有这些单独的信​​息。我想按姓名,年龄,地点对它们进行分类,以便我以后可以通过使用(年龄[0]。年龄[1]等)来访问它们。

到目前为止,这就是我所拥有的

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

我想知道如何能够在第二个空格之后存储剩余的信息,直到行结束。谢谢!!

2 个答案:

答案 0 :(得分:0)

std :: cin一般会在空格后断行,改为使用std :: getline():

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

答案 1 :(得分:0)

您正在阅读姓名和年龄值,但随后使用std::getline获取该行的其余部分,即位置。

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