我编写了一个程序,我想在其中获取用户的输入,如果按下“N”或“n”以外的任何键,程序将显示“HELLO WORLD”作为输出,否则将显示“正在退出”消息并退出。下面的程序在 Linux 中运行,但在 Dev-cpp windows 中不运行。即使在将 cin.get() 更改为 getchar() 之后也无法正常工作。该程序不等待用户输入。
我也在 cin.get() 之前添加了 system("pause"),但是每当按下一个键时它总是进入程序的其他部分。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
char ch ;
cout << "Press any key to continue, " << endl;
cout << "Press N or n to exit " << endl;
ch = cin.get();
if(ch == 'N' || ch == 'n')
{
cout << "Exiting " << endl;
exit(0);
}
else
{
cout << "HELLO WORLD" << endl;
}
return 0;
}
最佳答案
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
char ch ;
cout << "Press any key to continue, " << endl;
cout << "Press N or n to exit " << endl;
cin.get(ch);
if(ch == 'N' || ch == 'n'){
cout << "Exiting " << endl;
exit(0);
}
else{
cout << "HELLO WORLD" << endl;
}
return 0;
}
你可以试试 cin.get(ch),而不是 ch = cin.get()。
关于c++ - getchar 或 cin.get() 在开发 cpp 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967635/