为什么这个程序可以正常运行?
#include<iostream>
using namespace std;
int main()
{
cout <<"What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin>>address;
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
为什么这个程序不提供输入地址的机会?
#include <iostream>
int main()
{
using namespace std;
cout <<"What year was your house built?\n";
int year;
cin >> year;
cout << "What is its street address?\n";
char address[80];
cin.getline(address, 80);
cout << "Year built: " << year << endl;
cout << "Address: " << address << endl;
cout << "Done!\n";
return 0;
}
最佳答案
cin>>
在 iostream 中留下换行符 (\n)。如果在 cin>>
之后使用 getline
,getline
将这个换行符视为前导空格,认为它已完成并停止进一步读取。
解决问题的两种方法:
避免将 getline
放在 cin >>
之后
或
在调用 getline 之前,通过“抓取”它并将其放入“虚拟”变量中,使用 cin>> 中的尾随换行符。
string dummy;
getline(cin, dummy);
为什么第一个程序有效而第二个程序无效?
第一个程序:
cin
语句使用输入的年份并将 \n
作为垃圾留在流中。 cin
语句不会读取(或“抓取”)\n
。 cin
在读取数据时忽略 \n
。所以程序1中的cin
可以正常读取数据。
第二个程序:
getline
,读取并抓取\n
。因此,当它看到 cin
中遗漏的\n 时,它会获取 \n
并认为它已完成读取,从而导致第二个程序无法按预期运行。
关于c++ - C++中的混合数据类型输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799707/