C++ 使用cin获取带空格的多个输入

C++ 使用cin获取带空格的多个输入,c++,cin,C++,Cin,我有一个简单的结构,它存储需要通过用户输入初始化其值的人的详细信息。结构如下: typedef struct { char name[20]; int age; char address[50]; char vehicle[10]; }Runner; 我正在使用cin存储每个Runner的值,但希望在输入每个值后使用enter键获取输入(其中可能包含空格) 代码如下: Runner run1; cout <

我有一个简单的结构,它存储需要通过用户输入初始化其值的人的详细信息。结构如下:

typedef struct {

        char name[20];
        int age;
        char address[50];
        char vehicle[10];
}Runner;
我正在使用
cin
存储每个
Runner
的值,但希望在输入每个值后使用
enter键
获取输入(其中可能包含空格)

代码如下:

Runner run1;

        cout << "Enter name age address vehicle (pressing enter at each instance)" << endl;
        cin >> run1.name >> run1.age >> run1.address >> run1.vehicle ;
run1;
cout run1.name>>run1.age>>run1.address>>run1.vehicle;
很明显,空格分隔的值将被视为两个唯一的条目


如何仅在按下enter键后跳过空格和
cin
。另外,如果有其他方法处理此类情况,最好知道相同的方法。

因为输入之间可能有空格,所以应该使用getline函数

cin.getline (name,20);
cin.getline (address,50);
cin.getline (vehicle,10);
cin >> age;
cin.getline(run1.name,20);
cin.getline(run1.address,50);
cin.getline(run1.vehicle,10);
cin >> age
但是如果你想在取了name的值之后再取age的值,那么你必须这样做

cin.getline(run1.name,20);
cin >> run1.age;
cin.getline(dummy,5);    //cin leaves a newline at the buffer. This line of code takes the newline from the buffer.
cin.getline(run1.address,50);
cin.getline(run1.vehicle,10);

因为输入之间可能有空格,所以应该使用getline函数

cin.getline(run1.name,20);
cin.getline(run1.address,50);
cin.getline(run1.vehicle,10);
cin >> age
但是如果你想在取了name的值之后再取age的值,那么你必须这样做

cin.getline(run1.name,20);
cin >> run1.age;
cin.getline(dummy,5);    //cin leaves a newline at the buffer. This line of code takes the newline from the buffer.
cin.getline(run1.address,50);
cin.getline(run1.vehicle,10);

Runner
@GillBates的每个成员使用
std::getline
,因此我假设这不能像问题中所问的那样在一行中完成?对
Runner
@GillBates的每个成员使用
std::getline
,因此我假设这不能像问题中所问的那样在一行中完成?请您解释更多关于
dummy
您在代码中使用的东西?是的。cin从控制台获取输入。但在缓冲区中保留换行“\n”。和getline从缓冲区读取,直到找到换行符为止。因此,当您在cin之后立即使用getline时,第一个cin会留下一个换行符,然后getline会一直读到换行符(因此基本上,getline会读取一个空字符串)。因此,如果删除行cin.getline(dummy,5),run1.address将保存一个空字符串。因此,要从缓冲区中删除换行符,dummy使用换行符,run1.address具有正确的值。要了解更多信息,请阅读这个问题:以及Loki Askarico的评论,您可以解释更多关于您在代码中使用的
dummy
的内容吗?是的。cin从控制台获取输入。但在缓冲区中保留换行“\n”。和getline从缓冲区读取,直到找到换行符为止。因此,当您在cin之后立即使用getline时,第一个cin会留下一个换行符,然后getline会一直读到换行符(因此基本上,getline会读取一个空字符串)。因此,如果删除行cin.getline(dummy,5),run1.address将保存一个空字符串。因此,要从缓冲区中删除换行符,dummy接受换行符,run1.address有正确的值