simple calculator crash fix?

Hello and sorry in advance if this isn't the correct place for this. I'm very new to C++, I'm in college right now for it and I don't have the best teacher. With that said my assignment was to make a simple calculator to perform simple addition. The only issue is a requirement for it was that it didn't crash if letters were typed in. for example:
6potato should read the 6 and not any of the letters
I need it to be able to only read the integers in front of the letters, it's ok if it crashes if I typed potato6. Thanks in advance any help would be appreciated!


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
//This is a calculator designed to add
//Two integer Adder
//Shayne Thomas
//9/22/2021
#include <iostream>
using namespace std;

int main()
{
	int a, b, sum;
	cout << "\n\t\t\tTwo integer adder\n"
		<< "\t\t\tBy Shayne Thomas\n\n"
		<< " Please enter an INTEGER: ";

	cin >> a;

	cout << " Please enter another INTEGER: ";

	cin >> b;

	sum = a + b;
	cout << "the sum of " << a << " and " << b << " is " << sum << endl;

	return 0;
}
Last edited on
Using your example of 6potato, cin will get 6 just fine and return that to a.
cin >> b; will fail because Potato is still in the input buffer.

You have a couple of choices.
1) Use getline() to read "6Potato" and parse the number out of it.
2) Use cin.clear() and cin.ignore() to clear any errors and ignore any leftover characters in the input buffer.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

It looks you tried to use code tags, but your closing tag it wrong.
Last edited on
If you type "6potato 6", do you expect it to successfully output 12?

Anyway, to remove non-numbers from the input, you can do a while loop between the cin >> statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cctype>

// ...

    cin >> a;
    
    while (std::isalpha(cin.peek()))
    {
        char throwaway;
        cin.get(throwaway);
    }

    cin >> b;
    
Last edited on
Thanks for the help! The cin.get was exactly what I was missing. Sorry about the code, I fixed it literally made this account an hour ago, so thanks for putting that link in there.

Topic archived. No new replies allowed.