Problem with code

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>


short int x = 0;
short int 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;
	}
}
1
2
3
4
if (std::cin.fail()) {
		std::cout << "That is not a number\n";
		std::cin >> x;
	}

Should be :
1
2
3
4
5
if (std::cin.fail()) {
		std::cin.clear(); std::cin.ignore(1000, '\n');
		std::cout << "That is not a number. Enter another : ";
		std::cin >> x;
	}

> Why is this? Why does it ignore the cin?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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' ;

    // ...
}
Last edited on
Thank you very much, JLBorges. You have been a great help!
Topic archived. No new replies allowed.