【发布时间】:2014-01-02 22:30:31
【问题描述】:
我正在尝试制作一个程序来询问他们的名字,然后说“你好,(他们的名字)!”背部。 到目前为止,这是我的代码,“getchar()”只是让它暂停,我可以看到输出。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout<<"What is your name?:";
cin>>name;
cout<<"Hello, "<<name<<"!";
getchar();
return 0;
}
这要求我输入,我输入我的名字,然后应用程序关闭! 我不知道为什么以及如何解决它!请帮忙!
编辑: 找出解决方法。完成代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout<<"What is your name?: ";
cin>>name;
cout<<"Hello, "<<name<<"!\n";
system("PAUSE");
return 0;
}
【问题讨论】:
-
调用
getchar时,新行仍在流中,因此提取字符'\n'并关闭屏幕。 -
尝试在
getchar()之前使用std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');:几乎可以肯定,进入name的'\n'仍在缓冲区中。
标签: c++ visual-c++ io