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).
#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';
}