如何使用cin.get()检测空用户输入? [英] How can I use cin.get() to detect an empty user input?

查看:108
本文介绍了如何使用cin.get()检测空用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一些代码来检测空的用户输入:

I've written some code to detect empty user input:

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

但是由于某些原因,如果用户按ENTER键,那么在我按ENTER键时它只会继续前进到下一行.

But for some reason if the user presses ENTER it just keeps advancing to the next line as I press ENTER.

推荐答案

我认为这段代码可以完成您的工作.

I think this code does your job.

#include <iostream>
#include <sstream>

using std::cin;
using std::cout;
using std::string;

int main()
{
    string in = "";
    int n = 0;
    while (true)
    {
        cout << "Please enter a number: ";
        getline(cin, in);
        std::stringstream s(in);
        if (s >> n)
            break;
        cout << "Invalid number, please try again\n";
     }
     return 0;
}

AFAIK,我认为您不应该使用get()函数输入数字. get()函数旨在输入字符,其行为与未格式化的输入函数. >>运算符似乎更适合此工作.如果您按ENTER键,提取运算符>>将等待您的输入,因为它将忽略它.但是,换行输入存储在cin输入流中.您还可以尝试使用peek()seekg()函数的组合来检查输入流中是否存在现有的换行符,并执行所需的操作.

AFAIK, I think that you shouldn't use the get() function to input numbers. The get() function is designed to input characters and it behaves as an Unformatted Input Function. The >> operator seems better for this job. The extraction operator >> will wait for your input if you press the ENTER key because it will ignore it. However, the newline input is stored in the cin input stream. You can also try a combination of the peek() and the seekg() function to check for an existing newline input in the input stream and do what you want.

这篇关于如何使用cin.get()检测空用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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