I am writing a simple program to check if the input is an integer greater than 0. I have noticed that strings and characters get converted to zero when I do cin >> variable. So that means only integers above 0 can be validated. I don't need zero here anyway. Here is the code. My problem is the title.
1 2 3 4 5 6 7 8 9 10 11 12 13
std::cout << "Write an integer greater than 0:\n";
int n;
while(1){
std::cout << ">";
std::cin >> n;
if(n > 0){
break;
}
else{
std::cout << "You did not enter an integer greater than 0. Try again!\n";
}
}
std::cout << "You entered an integer greater than 0!\n";
My problem is that if I enter a wrong input, it keeps looping and looping the else branch. It does not let me input again. However, I have told it to get the input by that std::cin >> n; when the while, loops again.
I'm not sure what you are trying to accomplish with while(1)
while what is 1? You have to tell the compiler what you mean.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
int n;
cout << "Enter a number greater than 0:\n";
cin >> n;
while (n <= 0)
{
cout << "Integer not greater than 0. Please try again.\n";
cout << "Enter a number greater than 0:\n";
cin >> n;
}
return 0;
}
What I want to achieve with while(1) is an infinite loop.
Your method does not work either. Like in my method, the second time I try to store in n does not work. I noticed that it happens only when I enter a string or a character. It works fine when I enter 0. That means my earlier assumption that characters are converted to 0 is false.
I can't think of another way :/ . I will search google.
I still do not understand why its failing when I enter a character or a string.
The method I provided should loop until you enter an integer greater than 0. I can't remember if I tested it using a char or a string though. I'm not sure if I followed what you are trying to accomplish.
std::cout << "Write an integer:\n>";
int n;
std::cin >> n;
while (!std::cin) {
std::cout << "ERROR, you are allowed to enter an integer only.Try again!\n>";
std::cin.clear();
std::cin.ignore(10000,'\n');
std::cin >> n;
}
When the input is wrong, it's left in the buffer. We need to clear the input buffer using std::cin.ignore(). I don't really understand that function. Is it ignoring the first 10000 characters in the buffer? What's the use of the end of line character?
I have read the reference documentation in this site but I did not understand anything there.
@EssGeEich, yes. I am happy that I started using that way.
Oh right, you need to ignore it.
Basically it will erase up to 10000 characters, unless the newline character is found (it gets erased, too).
You should use std::numeric_limits<std::streamsize>::max() (include <limits>) instead of 10000: It is guaranteed to erase as much as possible.