C++ getline工作不正常?原因可能是什么?

C++ getline工作不正常?原因可能是什么?,c++,visual-c++,getline,C++,Visual C++,Getline,可能重复: 在我的程序中发生了一些独特的事情。 以下是一些命令集: cout << "Enter the full name of student: "; // cin name getline( cin , fullName ); cout << "\nAge: "; // cin age int age; cin >> age ; cout << "\nFather's Name: "; // cin father nam

可能重复:

在我的程序中发生了一些独特的事情。 以下是一些命令集:

 cout << "Enter the full name of student: ";  // cin name
 getline( cin , fullName );

 cout << "\nAge: ";  // cin age
 int age;
 cin >> age ;

cout << "\nFather's Name: ";  // cin father name
getline( cin , fatherName );

cout << "\nPermanent Address: ";  // cin permanent address
getline( cin , permanentAddress );
如果你注意到了,这个程序没有问我全名,而是直接问我年龄。然后它也跳过了父亲的名字,问了永久地址。 这可能是什么原因?


我很难发布整个代码,因为它太大了。

因为您没有发布任何代码。我要猜一猜

getline
cin
一起使用时的一个常见问题是
getline
不忽略前导空格字符

如果在
cin>
之后使用getline,则
getline()
会将此换行符视为前导空格,并且它会停止进一步读取

如何解决它?

调用
cin.ignore()
之前先调用
getline()


进行一个伪调用
getline()
,以使用
cin>

cin>>后的尾随换行符
输入缓冲区中仍然存在换行符
\n
(因为您按enter键输入值),要解决此问题,请添加一行
cin.ignore()
读取int.

后,问题是您将
getline
cin>
输入混合

当你做
cin>>年龄,它从输入流中获取年龄,但在流中保留空白。具体来说,它将在输入流上留下一个换行符,然后下一个
getline
调用将其作为空行读取

解决方案是只使用
getline
获取输入,然后解析该行以获取所需信息

或者,要修复代码,您可以执行以下操作,例如(您仍然需要自己添加错误检查代码):

cout年龄;
}

请把程序输出复制粘贴到你文章的格式化部分。图像具有随时间消失的特性,通常会产生红色十字。getline是否工作不正常@别有用心:哪些声明<代码>整数时代
,哪一个只将
std::string
作为目标<代码>cin
?真的没有理由用-1.+1进行心理调试。
ignore
的问题是你不知道需要忽略多少。最好只使用
getline
,一次只读取一行输入。或者:if(getline(cin>>ws,s2)){getline(cin,s2);}
Enter the full name of student:
Age: 20

Father's Name:
Permanent Address: xyz
cout << "Enter the full name of student: ";  // cin name
getline( cin , fullName );

cout << "\nAge: ";  // cin age
int age;
{
    std::string line;
    getline(cin, line);
    std::istringstream ss(line);
    ss >> age;
}

cout << "\nFather's Name: ";  // cin father name
getline( cin , fatherName );

cout << "\nPermanent Address: ";  // cin permanent address
getline( cin , permanentAddress );