4

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;
user2766873
  • 35
  • 1
  • 1
  • 4

2 Answers2

4

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;
        }
    }
}
galinette
  • 8,896
  • 2
  • 36
  • 87
0

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.

CommanderBubble
  • 333
  • 2
  • 9