C++为什么我用getline(cin,array[x])输入的第一个数据在同一条线上并且断开了,而我的第二个数据输入是


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

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

这是输出图像结果

为什么我的1个人数据被破坏了?姓名和地址在同一行,而我的第二人称数据还好吗?

如果我使用cin>gt;但我使用getline,这样我就可以用空格提供全名和地址

对于启动器可变长度数组

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

不是标准的C++功能。相反,使用类似的标准容器std::vector<std::string>

#include <vector>
//...
std::vector<std::string> name( person );
std::vector<std::string> adress( person );

或者,您可以声明一个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的新行字符CCD_ 3。你需要在while循环之前将其删除,就像一样

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

为此,您需要包含标头<limits>

相关内容

最新更新