Hey everybody. I made a calculator program today, and it works pretty well; but when you do something unexpected(like entering x, y, operator as opposed to x, operator, y) the program loops pretty much everything infinitely. Can anybody explain why this bug exists, and possibly point me in a direction of fixing it? Thanks in advance all.
I can't explain it very well, but I am pretty sure it's because of the >> operator you used to get the input stream. Try replacing all occasions of cin>>variable with getline(cin,variable), and it will probably work. At least that works for me. It has something to do with characters remaining in the input stream if you access it with cin>>...
Ah, and, unless you are planning to add additional options, don't you think that using the switch statement is kinda pointless here?
Ah no, I think getline will only accept strings as variable parameter. Try defining a string variable (for example, string input) which you give to getline as a parameter. Afterwards you can convert it into an integer with atoi (which requires a conversion into a C string first, example: int x = atoi(input.c_str());) or into a float with atof. If you get an error when defining a string variable, include string. (#include <string>)
To shadow addict: Yeah, that's possible. But if you want to use the same operation for numbers and operators, you will have to use strings cause numbers can have multiple digits, and can also have a + or - operator in front of them.
Wait... You can't define char variables, or you can't use them with any of the functions? I don't understand the problem...
You know what? Add cin.ignore(100,'\n') after every cin>>, and you should be able to use the initial program without any further modifications. (This pretty much does what it looks like, it will remove the next 100 characters from the input stream, or alternatively all characters until the next newline character. In your case, cin.ignore() will probably be already be enough (1 and EOF are the default values))