I've searched around here and on the internet for some solutions to this, but I can't seem to get it figured out. Basically, I am writing a very, very simple calculator-type program. As you'll see in my code I have it setup to give the user 4 options for operators, then it asks for two numbers, completes the operation and outputs, then prompts for another problem.
The problem I keep finding myself with is that if the user inputs a char instead of an integer the program infinitely loops. The problem only happens, however, if the user goes through the program twice.
eg.. I choose 1 for addtion, input 2 and 2. The program outputs 4 and asks if I have another problem. I input 1 for yes, then I input "a". *infinite loop*
This is my first program that I've ever tried on my own. I'm not using the best book (C++ for Dummies.... ) and I'm sure my code will receive a fair amount of criticism. But bring it on, please. I am open to any constructive things you can say.
The problem is you are putting in non-numerical characters and trying to read them into a double. This causes cin to go into an error state, and all successive reads will fail.
One way to fix this is read into a string and try to convert it manually:
Okay, so I haven't really studied too much further into C++ but I revised my code completely and came up with this. The problem I'm having now is when it asks which operation the user wants then you have to input your choice twice...
I know it's because of the loop I added to test the input at lines 49 - 59.
Ah blew my mind just now. ne555 had said that 70-74 was common to all operations and to put it only once, but for some reason my brain didn't even compute this. I was considering going back to pseudo-code which probably would have helped.
I'm still getting the loop though. If you go through one operation, then press 1 to choose again and THEN enter a letter it loops. I appreciate the help though. :D (still can't believe I missed that...)
Realised lines 134-138 (below) only needed once so 32-40 removed.
Got rid of 124-128. 126-130 added instead.
Changed [1] and [2] option to 'y' and 'n'. ie; line 116 int to char. line 121 if (loop = 'y') etc;