Code is bypassing imput.

Good Morning!

I have experience with scripting and linear programming, but I am having an issue with the code below and I hope someone can assist.

When executed, the programs runs as expected, unless a non-integer is used during cin >> a; - if a non-integer is used here, the code bypasses the cin >> b; and couts the INIT O and invokes the if(cin.fail()).

My question is: why does the program function in this manner?

All help is appreciated; code is below.

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
#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    int sum;

    cout << "Enter a number: ";
    cin >> a;
    cout << endl << "Enter another number: ";
    cin >> b;

    cout << endl << "INIT O";
    if(cin.fail())
    {
        cout << endl << "Not a number" << endl;
    }
    else
    {
        //nothing
    }
    sum = a + b;
    cout << sum;

    return 0;
}
You have to put the cin.fail() after the cin >> a; so that the compiler can read what failed from inputting into a variable first before it reaches b.

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
#include <iostream>
using namespace std;

int main()
{
	int a;
	int b;
	int sum;

	cout << "Enter a number: ";
	cin >> a;
	if (cin.fail())
	{
		cin.clear();
		cin.sync();
		cout << "\nNot a number.\n";
	}

	cout << "\nEnter another number: ";
	cin >> b;

	sum = a + b;
	
	cout << a << " + " << b << " = " << sum << endl;

	cout << endl;
	system("pause");

	return 0;
}


Even then, you would still require to add another function because a non-integer + a real-integer would give you a false result.
Last edited on
gomicoo,

Thanks - I know the program is faulty - I guess you could say I'm experimenting trying to find out how it works as I go. I didn't think the if statement would be called before it's time (so to speak) but I now understand it is a conditional whose parameters can be met anytime.

One thing about C++ is unlike other languages I've tried, there isn't a bunch of libraries loaded where the tutorial says "we'll worry about those later" - my brain can't' function that way - I need to know as I go. I can even look up the cin.clear and cin.sync above within this site's resources and learn.

Again, thanks - this is very much appreciated,

-K
Topic archived. No new replies allowed.