I have a problem with this code here. It's very simple and should work as I want. But after asking for the number of x, I created an if that triggers if the person didn't type in a number. It should ask me to type the number of cin again, but instead the program ends after saying "That is not a number" It completely ignores the std::cin x; in the if statement. Why is this? Why does it ignore the cin?
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
shortint x = 0;
shortint y = 0;
int main() {
std::cout << "What is the number one: ";
std::cin >> x;
if (std::cin.fail()) {
std::cout << "That is not a number\n";
std::cin >> x;
}
if (x != 0) {
std::cout << "What is the number two: ";
std::cin >> y;
while (x > y) {
std::cout << "Number not the same. Increasing the second number\n";
std::cout << "The second number is now: " << ++y << std::endl;
}
while (y > x) {
std::cout << "Number not the same. Increasing the first number \n";
std::cout << "The first number is now: " << ++x << std::endl;
}
if (x == y) {
std::cout << "The numbers are the same :D\n";
}
return 0;
}
}
When the attempt to read in a number fails, std::cin is placed into a failed state. A stream that is in a failed state would not perform any input or output till the failed state is cleared. https://stdcxx.apache.org/doc/stdlibug/29-1.html
The characters that formed the bad input remain in the input buffer; before we retry the input operation that failed, in addition to clearing the failed state, we need to remove these characters from the input buffer. std::cin.ignore( 1000, '\n' ) ; removes characters (maximum of 1000) from the input buffer up to the end of the line. http://en.cppreference.com/w/cpp/io/basic_istream/ignore
#include <iostream>
int main()
{
int x ;
std::cout << "first number? " ;
while( !( std::cin >> x ) ) // while the input of a number failed
{
std::cout << "that is not a number. try again: " ; // tell the user
std::cin.clear() ; // clear the failed state
std::cin.ignore( 1000, '\n' ) ; // extract and discard the invalid input
// go back and execute the loop once again
}
std::cout << "the first number is " << x << '\n' ;
// ...
}