开发者

Restrict users to enter numbers valid only till 2 decimal places C/C++

I am making an currency change program where I would be providing exact change to the input amount, for example a value of 23 would be one 20 dollars and 3 one dollar bills

I want to restrict the user to input the value only till 2 decimal places. For example: the valid inputs are 20, 20.4, 23.44 but an invalid开发者_StackOverflow中文版 input would be 20.523 or 20.000.

How can I do this is C/C++.

I read about one function that is setprecision but that is not what I want, setprecision allows to display the value till that decimal point, it still doesn't stop the user from entering any value.

Is there any way to do this?


Read the amount from the user as a string, either character by character or the entire line, and then check its format, and then convert it.


It's generally easier to let the user type whatever they want followed by the program rejecting the input if it isn't valid rather than restricting what they can type on a keystroke basis.

For keystroke analysis you would need a state machine with 4 states, which we can call Number, Numberdot, Numberdotone, and Numberdottwo. Your code would have to make the proper transitions for all keystrokes, including the arrow keys to move the cursor to some arbitrary place and the Backspace key. That's a lot of work.

With input validation, all you have to do is check the input using a regular expression, e.g. ^(([0-9]+) | ([0-9]+.[0-9]) | ([0-9]+.[0-9][0-9])$. This assumes that "20." is not valid. Then if it's invalid you tell the user and make them do it again.


I do not believe that there is any way to set the library to do this for you. Because of that you're going to have to do the work yourself.

There are may ways you can do this, but the only true way to handle restricting the input is to control reading it in yourself.

In this case you would loop on keyboard input, for ever keystroke you would have to decided if it can be accepted in the context of the past input, then display it. That is, if there is a decimal point you would only accept to more numbers. This also allows you to limit input to numbers and decimal places as well, not to mention input length.

The down side is you will have to handle all the editing commands. Even bare bones you would need to support delete and enter.


This is rather a task for the GUI you are using, than for core C/C++. Depending on your GUI/Web Toolkit you can give more or less detailed rules how data can or can not be entered.

If you are writing a normal GUI application you can control and modify the entered keys (in C or C++). In a WEB application you can do similar things using javascript. The best solution would be when all illegal input is impossible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜