The problem is when i enter wrong input, like 5z, it first prints " b: " and than it prints "invalid input"
But it's suppose to print" invalid input "just after i entered something wrong.
It works normally if I type " z5 " , but it doesnt if i type " 5z ".
cin works like a queue.
If you ask cin to read a double it will try to do so and if it can remove this for it's queue.
So with the input of '5z' it will read in 5, remove it and moves on to cout << "b: ", then the 2nd time you do a cin it will find the remaining 'z' and your code will print out "invalid input".
To fix this, what i do is always have cin put whatever is in the queue in a string, and parse the data myself. This will make sure that '5z' will be detected as invalid by your parser and that the entire input gets used and not only up till the point where the input is valid.
If you don't care about your program seeing '5z' as valid you can use cin.ignore() to empty the queue before every use. But then your program will see '5z' as being the double 5, but it will not pass the remaining 'z' on to your next cin.
Oke, i got that, but i don't want to be a valid read anything except the numbers. So, if some letter is entered, print "invalit input"
Also, in your case it just ignores the z, but if i write 5zz, its same again :/
cout << "a: ";
cin >> a;
if(a <= 0)
{
cout << "invalid input\n";
system("pause");
return 0;
}
char p = cin.get(); // here we try to get the next char in the queue.
if (cin.good()) // If cin.get() was successful there was more in the queue then just a double
{
cout << "invalid input\n";
system("pause");
return 0;
}
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
This is not the safest way to do this, there may be leftover white-spaces or end-of-line chars in the queue that will kill your program.
As I was saying, the safest way to do this is to put everything in a string by using getline(cin, string) and write your own parser to parse the string to a double.
Also, in your case it just ignores the z, but if i write 5zz, its same again :/
Yes sorry cin.ignore() removes one entry to clear the buffer there are 2 ways:
1) Ignore to the end of file:
cin.ignore(std::numeric_limits<std::streamsize>::max()) or cin.flush()
2) Ignore to the end of line:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')