c++ - getchar 或 cin.get() 在开发 cpp 中不起作用

标签 c++ dev-c++

我编写了一个程序,我想在其中获取用户的输入,如果按下“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/

相关文章:

c++ - 在 boost 元组、zip_iterator 等上使用 std::get 和 std::tie

c++ - 在编译时创建一个包含行号的标识符

c - MAX 值过大的程序崩溃案例

c++ - 如何将模式从 Dev-C++ 中的 c++98 模式更改为支持 C++0x 的模式(基于范围)?

c++ - Orwell Dev-C++ fatal error : "iostream: no such file or directory"

c - 源文件 没有这个目录?

c++ - 使用递归和乘法将 C 代码转换为 MIPS 问题

c++ - 程序结束时进程返回 0xC0000005

c++ - 当我将两个头文件链接在一起时,一个无法识别另一个

c - 使用 Horner 方法求多项式导数的函数错误在哪里?