在 C++如何区分整数和字符?
我目前正在学习 C++,有人要求我编写一个程序来计算给定大小的存款所支付的利息。要求之一是在输入非整数数据时显示错误消息。
然而,我无法弄清楚如何检测是否输入了非整数数据。如果有人可以提供如何解决此问题的示例,将不胜感激!
I am currently learning C++ and I have been asked to make a program which will calculate the interest that would be paid on a deposit of a given size. One of the requirements is that we display an error message when non-integer data is entered.
I however cannot work out how to detect if non-integer data has been entered. If anyone could provide an example of how this problem is solved it would be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不必检查自己。表达式
(std::cin >> YourInteger)
计算结果为 bool,当且仅当成功读取YourInteger
时,该表达式才为 true。这导致了这个成语You don't have to check yourself. The expression
(std::cin >> YourInteger)
evaluates to a bool, whcih is true if and only ifYourInteger
was succesfully read. This leads to the idiom这应该是一个足够清晰的起点。
this should be a clear enough starting point.
您需要查明输入值是否包含非数字字符。也就是说,除了 0-9 之外的任何数字。
您必须首先将输入作为字符串,然后验证每个数字是否确实是数字。
您可以使用
中定义的内置函数 isdigit() 迭代字符串并测试每个字符是否为有效数字。如果您使用的是十进制数字,您可能还需要允许使用单个逗号。You need to find out if the input value contains non numeric characters. That is, anything other than 0-9.
You have to first take input as string and then verify if every digit is indeed numeric.
You can iterate the string and test if each character is a valid digit using the built in function isdigit() defined in
<cctype>
. You might also want to allow for a single comma if you're working with decimal numbers.