C++ 上的整数验证
我编写了小型 C++ 控制台应用程序,这是源代码:
#include<stdio.h>
#include<locale.h>
#include<ctype.h>
#include<stdlib.h>
void main()
{
setlocale(LC_ALL, "turkish");
int a,b,c,d;
printf("first number: ");
scanf("%d", &a);
printf("second number: ");
scanf("%d", &b);
c = a+b;
printf("Sum: : %d\n", c);
}
如您所见,我向用户请求两个数字,然后将它们相加。但我想添加一个控件,其中用户输入的检查号码是整数?
我将检查用户输入的数字,如果数字不是真正的整数,我将回显错误。我在每次 scanf
之后使用它,但效果不是很好。
if(!isdigit(a))
{
printf("Invalid Char !");
exit(1);
}
不久之后,在 scanf 操作中,如果用户键入“a”,它将产生一条错误消息并且程序停止工作。如果用户输入数字程序将继续
I have written small C++ console application and this is source code :
#include<stdio.h>
#include<locale.h>
#include<ctype.h>
#include<stdlib.h>
void main()
{
setlocale(LC_ALL, "turkish");
int a,b,c,d;
printf("first number: ");
scanf("%d", &a);
printf("second number: ");
scanf("%d", &b);
c = a+b;
printf("Sum: : %d\n", c);
}
As you can see i'm requesting two numbers from user and than summing them. But i want to add a control which check number who enterede by user is integer?
I'll check number which typed by user and than if number isn't really a integer i will echo an error. I'm using this after every scanf
but it's not working very well.
if(!isdigit(a))
{
printf("Invalid Char !");
exit(1);
}
In shortly, on a scanf action, if user type "a" it will produce an error message and program stop working. If user type a number program will continue
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
scanf
会为您进行验证。只需检查scanf
的返回值即可。scanf
does that validation for you. Just check the return value fromscanf
.执行此操作的 C++ 方法是
The C++ way to do this would be
isdigit
采用char
作为参数。如果对
scanf
的调用成功,则保证您拥有一个整数。scanf
还有一个返回值,指示它已读取了多少个值。在这种情况下,您想要检查
scanf
的返回值是否为 1。请参阅:http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
isdigit
takes achar
as an argument.If the call to
scanf
succeeds, you're guaranteed that you have an integer.scanf
also has a return value which indicates how many values it has read.You want to check if the return value of
scanf
is 1 in this case.See: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/