在C ++中检测ENTER键 [英] Detecting ENTER key in C++

查看:59
本文介绍了在C ++中检测ENTER键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的程序,

I have a program like this,

char name[100];
char age[12];
cout << "Enter Name: ";
cin >> name;

cout << "Enter Age: ";
cin >> age;

现在年龄是一个可选字段,因此用户只需按ENTER键并将该值设置为NULL.但是问题是,cin不带ENTER键,而只是呆在那里等待有效的键盘字符或数字输入.

Now age is a optional field, so user can simply press ENTER key and have that value as NULL. But the problem is, cin doesn't take ENTER key and just stay there waiting for a valid keyboard char or numerical input.

我认为问题是因为cin需要有效的输入,因此永远存在.

I think the problem is because cin needs a valid input and thus stays there forever.

所以我尝试了以下方法来检测年龄的ENTER键.

So i tried below approach to detect ENTER key press for Age.

cout << "Enter Age: ";
if (cin.get() == '\n') {
            cout << "ENTER WAS PRESSED" << endl;
        }

现在,用户输入名称后只要按ENTER键,它将直接进入IF条件.

Now as soon as user presses ENTER key after entering a NAME, it goes straight to the IF condition.

我也尝试过:

getline(cin, age);

但是,这也不只是在 cout<<"Age:"; 等待用户的输入.

But that also simply doesn't stop at cout << "Age: "; waiting for an input from the user.

用户可以输入有效年龄,也可以直接按Enter键而不输入年龄.

The user can either a valid age or simply press ENTER key not to enter a age.

对于以下代码:

cout << "Enter Name: ";
        cin >> name;

        cout << "Enter Age: ";
        if (cin.get() == '\n') {
            cout << "ENTER WAS PRESSED" << endl;
        }

输出为:

Enter Name: asdf
Enter Age: ENTER WAS PRESSED

我希望光标在 Enter Age:_

我该怎么做?

推荐答案

您尝试过吗?:

cout << "Press Enter to Continue";
cin.ignore();

还要查看此问题

这篇关于在C ++中检测ENTER键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆