I want c++ to loop this if its not a number, giving the user a chance to correct the errors. I also tried using failbit flag in an if statement to give an error message, but then the loop got infinite, dont know how to use failbit.
My code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
int num;
std::cout << "Give number: ";
do
{
std::cin >> num;
}while(std::ios::goodbit || !num < 0);
std::cout << "Number is: " << num;
}
When I enter 4455 it will exit the loop and print 4455, no problems there. But if I enter 1122ff it will exit the loop and print 1122. It should not exit the loop if the input is wrong, it is supposed to let me give a new number. Why doesnt it?
std::ios::goodbit is a constant value. It will never change. The loop conditional may as well be while (true).
When you enter something like "1122ffn\n" and tell cin you're extracting a number, 1122 will be extracted from the stream and the "ff\n" will be left in. That's just the way streams work. If you want to accomplish the behavior you describe, you'll need to do a bit more work.
!num < 0 will never be true, btw.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <limits>
int main()
{
int num;
std::cout << "Give number: ";
while ( std::cin >> num && std::cin.peek() != '\n' )
{
std::cout << "Invalid input. Enter a number: " ;
std::cin.clear() ;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') ;
}
std::cout << "Number is: " << num << '\n' ;
}