C++ Fix for checking if input is an integer [duplicate]

倖福魔咒の 提交于 2020-02-15 08:02:12

问题


for example, if I enter "2a", it does not show an error nor asks the user to re-input the value. how do i fix this?

while (std::cin.fail())
{ 
    std::cout << "ERROR, enter a number" << std::endl;
    std::cin.clear();
    std::cin.ignore(256,'\n');
    std::cin >> dblMarkOne;
}
std::cout << "" << std::endl;

回答1:


Two possible solutions:

  1. First store the input in a std::string instead of directly to an int. Then, use strtol from for converting to an integer. If the endPtr points to 0, it means nothing is left at the end, so this is OK. Otherwise, some no number characters are found at the end
  2. In your example, std::cin >> dblMarkOne; will leave non-number characters in std::cin, so if there is still data available in std::cin after, for instance by using std::cin.peek()!=EOF, this means the user has entered more than a number.

Edit : full tested code:

#include <iostream>
#include <cstdio>

int main(int argc, char ** argv)
{
    bool ok = false;
    int dblMarkOne;
    std::cout << "Enter a number" << std::endl;
    while (!ok)
    { 
        std::cin >> dblMarkOne;

        if(!std::cin.fail() && (std::cin.peek()==EOF || std::cin.peek()=='\n'))
        {
            ok = true;
        }
        else
        {
            std::cin.clear();
            std::cin.ignore(256,'\n');
            std::cout << "Error, Enter a number" << std::endl;
        }
    }
}



回答2:


One way would be to use the isDigit() function.

It returns a 1 for characters that are numbers in ascii and 0 otherwise.

How to use it would depend on whether you're expecting a single digit and are only checking that or want a longer number.

If you want to extract the number characters that occur until a non-number character occurs, store it to a char[] or std::string, then iterate over each character, either discarding characters you don't want or exiting at the first other character.

if you're only after a single digit, modify your loop to something like this:

std::cin >> dblMarkOne;

while (!isDigit(dblMarkOne)) {
    std::cout << "ERROR, enter a number" << std::endl;
    std::cin.clear();
    std::cin.ignore(256,'\n');
    std::cin >> dblMarkOne;
}

if you wanted a longer-than-one-digit number, just create a std::string to hold the input and iterate over its contents based on whether you want to break early or not, and store the output to your variable.



来源:https://stackoverflow.com/questions/18767800/c-fix-for-checking-if-input-is-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!