Help with Input

Hi, I have a quick question to for my programming homework. So what I have to do is see if 3 of these numbers create a triangle, which they do, and it works perfectly.

Though, I want to make it more user friendly. The problem is that if you enter in a letter or a word/sentence instead of a digit, the program just crashes.

My question: How can I make a simple "if" statement there saying that you didn't enter in a digit? I marked where I want to put it.

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
37
38
39
40
41
42
43
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()

{

	int a;
	int b;
	int c;

	cout << "Enter the three sides of a triangle: " << endl;
	cout << "-===================================-\n" << endl;

****HELP HERE**** if (input != an inputted number)****HELP HERE****


	cout << "A.) ";
	cin >> a;
	cout << "B.) ";
	cin >> b;
	cout << "C.) ";
	cin >> c;

	if (c < a + b && a < b + c && b < a + c)

		cout << "Works" << endl;

	

	else 

		cout << "Doesn't work" << endl;


	

	system("PAUSE");

}

You can do something like this:

1
2
3
4
5
6
while( std::cout << "Enter an integer: " && !(cin >> input) ) //if the input failed
{
    std::cin.clear(); //clear error flags
    std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); //ignore all the left over characters in buffer until next line found
    std::cout << "Invalid input - Did not enter an integer." << std::endl;
}


Some helpful links:
http://www.cplusplus.com/reference/ios/ios/clear/
http://www.cplusplus.com/reference/istream/istream/ignore/?kw=cin.ignore
http://www.cplusplus.com/reference/limits/numeric_limits/?kw=numeric_limits

*missing parenthesis

One thing to mention the best solution would probably to read as a string then parse. Because this method might have a few bugs if you mix letters and numbers.
Last edited on
Thank you so much, sir!
Topic archived. No new replies allowed.