1

I am using a function to check that my input in an integer only:

    int input;
    while (true)
    {
        std::cin >> input;
        if (!std::cin)
        {
            std::cout << "Bad Format. Please Insert an integer! " << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            continue;
        }
        else
            return input;
    }

However when inputing a integer followed by a char, eg. 3s, the integer gets accepted and the message gets printed.

How can I make sure that the input in such format does not get accepted, nor do input in form 4s 5, so when the integer appears after the space.

3
  • std::getline and unsure parsed line is empty afterward? Commented May 27, 2020 at 7:43
  • 1
    char is also an int Commented May 27, 2020 at 7:44
  • 1
    std::cin into a string and validate the string using regex or something. Commented May 27, 2020 at 7:44

2 Answers 2

5

That happens because chars in c++ are represented by their numeric value in the ascii table, you can try regular expressions like this:

#include <regex>
#include <string>
    std::string str;
    std::regex regex_int("-?[0-9]");
    while (true)
    {
        std::cin >> str;
        if (regex_match(str, regex_int))
        {  
           int num = std::stoi(str);
           //do sth
           break;
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Fixed the problem Thank you.
"That happens because chars in c++ are represented by their numeric value" No, here, the issue is that std::cin >> input; stops once int has been read (so it remains extra char in std::cin).
0

There's no need for a regular expression that duplicates the validation that std::stoi does. Just use std::stoi:

std::string input;
std::cin >> input;
std::size_t end;
int result = std::stoi(input, &end);
if (end != input.size())
    // error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.