Creating a program that ignores string input/reprompts user for correct input

I'm very new to C++ and am working on writing an extremely simple calculator program that takes two doubles and one of the four mathematical operators as input and outputs the result. I have successfully coded that part. However, I wanted to take it a step further and code the program so that it will not accept string input/anything other than char/doubles.

A note on the header I'm using- I'm learning from Stroustrup's "Programming: Principles and Practice" which requires that specific header for the first few chapters (the reason it has a 2 in the name is a long, useless story).

I'm using Windows 7, compiling with Visual Studio 2013.

I have tried various methods that, in theory, should prevent a program from accepting string input however none of these seem to have worked (ie. !cin or cin.fail() ) were two answers I found via Google but didn't seem to do anything for my program.

When this code is run, the calculator portion of it works correctly (ie. inputting 1 + 5 will return "The sum of 1 and 5 is 6" and then ask the user to input another problem) but when a string is entered, the program ignores my else if statement that should restart the loop asking the user to enter a number.

I have tried other methods to make the program reject the string input and can upload the code for those as well if need be.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "std_lib_facilities2.h"
#include "std_lib_facilities.h"
int main()
{
	//have user input 3 arguments: 2 double values, one assignment operator.
	//ie. If the entry arguments are 35.6, 24.1, and '+', the program output should be The sum of 35.6 and 24.1 is 59.7.

	double num1 = 0; //initializing variables
	double num2 = 0;
	char assiOp = 0; //char will be one of 4 operators
	double sum = 0;
	double difference = 0;
	double divBy = 0; //initializing responses
	double multBy = 0;
	string strNo = ""; //initializing empty string which will be used to check if user enters anything but a double/char


	cout << "Enter two numbers with an operator in between (+, -, /, *):" << endl; //asking for user input

	while (cin >> num1 >> assiOp >> num2 || cin >> strNo){ //while loop asks for user input and continues asking for input after each subsequent question is answered
	
			if (assiOp == '+'){ //SINGLE QUOTES FOR CHARS
				sum = num1 + num2; //does the work
				cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl;
			}

			else if (assiOp == '-'){
				difference = num1 - num2;
				cout << "The difference between " << num1 << " and " << num2 << " is " << difference << endl;
			}

			else if (assiOp == '/'){
				divBy = num1 / num2;
				cout << num1 << " divided by " << num2 << " is equal to " << divBy << endl;
			}

			else if (assiOp == '*'){
				multBy = num1 * num2;
				cout << num1 << " multiplied by " << num2 << " is equal to " << multBy << endl;
			}

			else if (cin >> strNo){ //this else if statement seems to be ignored and when a string is entered the program goes strait to "Press any key to continue"
				cout << "Sorry I don't recognize your input." << endl;
			}

			else{ //if anything except for double/char input, this should be output, however does not work when string is input- goes directly to system(pause)
				cout << "Sorry I don't recognize your input." << endl;
			}

			cout << "Enter two numbers with an operator in between (+, -, /, *):" << endl;
		}

	system("pause"); //keeps window open
	return 0;

}


Thank you in advance for any insight.
For the failbit flag style, I don't know how you went about it but this is one way to do it:
1
2
3
4
5
6
7
8
9
10
11
int i=0;
start:
cout«"Enter an integer: ";
cin»i;
if(cin.fail()) {
     cerr«"\nBad input";
     cin.ignore();
     i=0;
     cin.clear();
     goto start;
}


So you basically check if the input stream has failed, if yes ignore whatever is in the buffer, reset my int, clear the flags and start over again.


Aceix.
Last edited on
I use a similar function all the time, works just fine for me. You can try it out.
I made it a template so it can be used with any data type.

1
2
3
4
5
6
7
8
9
10
template<typename dataType>
void cin_validation(dataType &d){
    while(!(cin>> d)){    //  If the user inputs the wrong data type they will be given an error and will have to re-enter input until correct.
        cout<< "Error: Invalid Input.\n"
        << "Please try again: ";
        cin.clear();    //  Clears cin flags if user enters the wrong data type.
        cin.ignore(100, '\n');  //  Ignores up to 100 characters or until a new line.
    }
}
Thank you both for your replies though I feel both are a little advanced for me so I'm not entirely sure I'm understanding correctly. However I'm going to do some research on the terminology used in the solutions and attempt to edit them to fit my needs/this particular program.
(Truthfully I don't even know how to use templates yet but I'll figure it out.)
Thanks again.
Last edited on
Templates are pretty simple, you could watch a 3 minute youtube video on them and you'd be just fine! Good Luck!

Also basically what mine is saying is, While d is not of type datatype then it is going to run through that while loop and ask you to keep re-entering input until you input a value of type datatype. You could use the function without making it a template as well but you'd have to replace datatype with float, int etc.. and overload it for each new data type you want to use it with.
Last edited on
Topic archived. No new replies allowed.