本文介绍了扫描数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 C 语言的新手,我有一个关于仅用于数字的 scanf 的问题.我需要做的是输入只有 3 位数字的 scanf,其他字符或符号应该被评估为垃圾.或者我可能需要使用 isdigit()
但我不确定它是如何工作的.我就是这样,但我知道它不起作用:
I am pretty new in C and I have a question about scanf just for digits. What I need to do is scanf in input just 3 digits, antoher characters or symbols should be evaluate as trash. Or maybe I need use isdigit()
but I am not sure how it works. I have just that, but I know that it doesn't work:
scanf("%d, %d, %d", &z, &x, &y);
推荐答案
您可以读取一个字符串,使用扫描集对其进行过滤并将其转换为整数.
You could read a string, use a scan set to filter it and convert it to an integer.
参见 scanf:http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char num1[256], num2[256], num3[256];
scanf("%s %s %s", num1, num2, num3);
sscanf(num1, num2, num3, "%[0-9]d %[0-9]d %[0-9]d", num1, num2, num3);
int n1 = atoi(num1), n2 = atoi(num2), n3 = atoi(num3); // convert the strings to int
printf("\n%d %d %d\n", n1, n2, n3);
return 0;
}
样本输入 &输出:
Sample Input & Output:
2332jbjjjh 7ssd 100
2332 7 100
这篇关于扫描数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!