如何使用cin实现单行整数类型命令行输入验证? [英] How do I implement single line integer type command line input validation using cin?

查看:65
本文介绍了如何使用cin实现单行整数类型命令行输入验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,要求用户输入[0,2]范围内的整数.我使用以下链接作为指南.

I have a program which asks the user to input an integer in the range [0,2]. I used the following link as a guide.

使用cin-C ++的良好输入验证循环

但是,当用户在不输入数据的情况下按Enter键时,光标仅会跳至命令提示符下的下一行,而我希望它提示用户输入有效数字.在这种情况下提示用户是否有意义,还是有理由不将验证作为开始的单行输入来实现?在使用字符串的情况下,我将使用getline解决此问题,在这种情况下,是否应该以某种方式使用它?这是我的代码,基于上面的链接:

However, when the user presses enter without inputting data the cursor simply goes to the next line in the command prompt whereas I would prefer it to prompt the user to enter a valid number. Does prompting the user in this case make sense, or is there a reason not to implement validation as single line input to begin with? In the case of strings I would use getline to solve this, should I use that somehow in this case? Here is my code, based on the above link:

#include <iostream>

int main()
{
    int answeredNumber;
    while(1)
    {
        std::cout << "Enter your answer: ";
        if(std::cin >> answeredNumber && answeredNumber >= 0 && answeredNumber <= 2)
        {
            break;
        }
        else
        {
            std::cout << "Please enter a valid answer: " ;
            std::cin.clear();
          std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    system("pause");
}

推荐答案

这是因为使用 cin 获取整数会跳过前导空格,其中包括换行符.没有简单的方法可以解决这个问题.

That's because getting an integer with cin will skip leading whitespace, including a newline. There's no easy way around that.

如果要基于行的输入,则可以将输入值作为 string 来获取,然后解释为:

If you want line-based input, you can get your input value as a string and then interpret that:

#include <iostream>
#include <sstream>
#include <string>

int main (void) {
    std::string inputLine;
    int answer;
    std::cout << "Enter your answer: ";
    while(1) {
        getline (std::cin, inputLine);
        std::stringstream ss (inputLine);
        if ((ss >> answer))
            if ((answer >= 0) && (answer <= 2))
                break;
        std::cout << "No, please enter a VALID answer: " ;
    }
    std::cout << "You entered " << answer << '\n';
    return 0;
}

这篇关于如何使用cin实现单行整数类型命令行输入验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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