Int allow only numbers

Hello guys,

i wanted to ask if its is possible that an integer accepts only numbers. Because when you type for example a letter it just bugs and shows the cout all the time in a loop. Thanks in advance
An integer is a thing. It merely holds a state. It's not a process, so it's not capable of accepting or rejecting anything.

If you do this:
1
2
int n;
std::cin >> n;
and the user enters something that's not a number, n will remain in an undefined state.
If you want to ensure that the user can only enter a number, you can do
1
2
3
4
int n;
std::cout << "enter a number\n";
while (!(std::cin >> n))
    std::cout << "no, a NUMBER\n";
You can do something like this, although it will allow input like 1234abcd, assigning 1234 to n. You could add more tests to check that, too. It also says "That's not a number!" if you enter a number that's too large (which also causes cin >> to fail).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <limits>

void clean_input(std::istream& in) {
    // clear the error state of the stream
    in.clear();
    // remove everything up to and including the newline
    in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

int main() {
    int n;
    while (true) {
        std::cout << "Number: ";
        if (std::cin >> n)
            break;
        std::cout << "That's not a number!\n";
        clean_input(std::cin);
    }
    clean_input(std::cin);
    std::cout << "You entered: " << n << '\n';
}

Or maybe this is better:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <sstream>
#include <string>

int read_int(const std::string& prompt) {
    int n;
    while (true) {
        std::string line;
        std::istringstream iss;
        while (true) {
            std::cout << prompt << ": ";
            std::getline(std::cin, line);
            iss.str(line);
            if (iss >> n)
                break;
            std::cout << "That's not a number!\n";
            iss.clear();
        }
        line.clear();
        iss >> line;
        if (line.empty())
            break;
        std::cout << "Extraneous characters after the number\n";
    }
    return n;
}

int main() {
    int n = read_int("Enter a number");
    std::cout << "You entered: " << n << '\n';
}

Last edited on
Topic archived. No new replies allowed.