C++ 为什么我用 getline(cin, array[x]) 输入的第一个数据在同一条线上并且损坏了,而我的第二个数据输入没问题?

C++ Why is my first data input with getline(cin, array[x]) is on the sameline and broken while my 2nd data input is fine?

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int person;
    cout << "How many person to data: ";
    cin  >> person;

    int x = 0;
    int i = 1;
    string name[person];
    string adress[person];

    while(x < person){
        cout << i << " person data" << endl;
        cout << "Name: ";
        getline(cin, name[x]);
        cout << "Adress: ";
        getline(cin, adress[x]);
        cout << endl;
        x++, i++;
    }

    for(x=0; x<person; x++){
        cout << name[x] << setw(15) << adress[x] << endl;
    }
}

这是我的代码,用于将名称和地址存储到数组 name[] 和 address[] 中 然后我使用 for 循环打印他们的名字和地址

这是输出图像 Result

为什么我的1人资料坏了? 姓名和地址在同一行,而我的第二人称数据没问题?

如果我使用 cin 没问题 >> 但我使用 getline 所以我可以输入全名和带空格的地址

对于初学者可变长度数组

string name[person];
string adress[person];

不是标准的 C++ 功能。而是使用标准容器 std::vector<std::string> like

#include <vector>

//...

std::vector<std::string> name( person );
std::vector<std::string> adress( person );

或者您可以声明 objects 类型 std::pair<std::string, std::string> 的向量而不是两个向量,例如

#include <utility>
#include <vector>

//...

std::vector<std::pair<std::string, std::string>> persons( person );

在这种情况下你应该在循环中写成

    //...
    getline(cin, persons[x].first );
    //...
    getline(cin, persons[x].second);

输入后

cin  >> person;

输入流包含对应于按下的 Enter 键的换行符 '\n'。您需要在 while 循环之前将其删除,例如

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

为此,您需要包含 header <limits>.