You are here:

C++/C++ question


I'm building a calculator program, that has the user first input an operator, then a number. I'm using a SENTINEL loop so that if the user inputs a q it will exit. My problem is that I need to make it non crashable. So I need to restrict the user to only inputing operators I that i accept without letters, and only valid numbers "not letters". Sorry sounds so confusing. thanks

If you're getting keys, test each key and decide what to do (I'd use a switch statement as they are efficient and the default case can catch all the bad input.  If you're inputting strings, you can use a loop with a pointer and do it one character at a time.  Use a state variable to know what you're inputting.  Change state when the input is OK. First state could be 1 for operator, stay in state 1 until the user enters an operator or q.  If you get q, quit.  If you get an operator, go to state 2 for number.  State 2 looks for 0-9 only, or q to quit and gives an error on anything else (maybe Return to end the number?).

Write down what you would do if you had to do this "by hand".  When you know what you have to do to satisfy the requirement, you know how to tell the computer to do the job.  


All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2016 All rights reserved.