Reputation: 151
I'm creating my own very simple program that allows the user to input a numeric value. At the moment the code works just fine, but I need a validation if else statement. This is what I have at the moment;
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned __int64 input = 0;
char str[] = "qwertyuiopasdfghjklzxcvbnm[]{};'#:@~,./<>?|!£$%^&*()";
cout << "Insert a number" << endl;
cin >> input;
if (input % 2 == 0)
{
cout << "Even!" << endl;
}
else
{
if (input% 2 == 1)
{
cout << "Odd" << endl;
cout << "Lets make it even shall we? " << "Your new number is... " << input + 1 << endl;
}
else if (isdigit(str[0]))
{
cout << "That isn't a number!" << endl;
}
}
system("pause");
return 0;
}
The issue I am having is that if the user inputs anything that isn't a number, the value it returns is "Even".
I hope you guys and girls can help! John
Upvotes: 0
Views: 533
Reputation: 476940
Don't use token extraction (>>
) for primary parsing. Once the extraction fails, your primary input is left in an unspecified state, which is terrible. Instead, read the input line by line and then process each line.
Also, never ignore the result of an input operation. That's just a flat error.
So, putting all this together, here's how you could handle this:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
for (std::string line; std::cout << "Input: " && std::getline(std::cin, line); )
{
std::cout << "We're parsing your line '" << line << "'\n";
int n;
std::istringstream iss(line);
if (iss >> n >> std::ws && iss.get() == EOF)
{
std::cout << "It was a number: " << n << "\n";
}
else if (line.empty())
{
std::cout << "You didn't say anything!\n";
}
else
{
std::cout << "We could not parse '" << line << "' as a number.\n";
}
}
std::cout << "Goodbye!\n";
}
Note that all input operations (namely >>
and getline
) appear in immediate boolean contexts!
Upvotes: 4