Reputation: 397
I'm trying to get input for an integer in C++ through cin
and when I try this:
int port = 0;
do
{
std::cout << "Enter port for server: ";
std::cin >> port;
} while (port <= 0);
It spams my terminal with "Enter port for server: " if I don't enter a valid integer. How do I handle this situation and why does this spam my terminal?
Upvotes: 0
Views: 3057
Reputation: 427
if (std::cin.fail())
{
std::cout << "Enter valid port, please. " << std::endl;
}
while (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::cin >> port;
}
After std::cin fails, you need to clear error flag. You don't even have to use fail function:
while (!(std::cin >> port)) { std::cin.clear(); std::cin.ignore(); }
Upvotes: 1
Reputation: 3613
You're not validating input. Ideally what you should do is take input as strings then perform the conversion to the type you want after. If you do want to take them as integers, You can check the value of cin after the user enters input. If input is invalid, the failbit in cin is set.
int main(){
int port = 0;
do
{
std::cout << "Enter port for server: ";
if(!(cin >> port)){//error occurred
std::cout << "invalid input" << std::endl;
cin.clear();//Clear the error
break;
}
} while (port <= 0);
}
Upvotes: 2