C语言 如何在C中检查给定的字符串是否仅包含数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14422775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a given string contains only number or not in C
提问by DNU Dev
How to check a given string contains only number or not?
如何检查给定的字符串是否只包含数字?
回答by
You can use the isdigit()macro to check if a character is a number. Using this, you can easily write a function that checks a string for containing numbers only.
您可以使用isdigit()宏来检查字符是否为数字。使用它,您可以轻松编写一个函数来检查字符串是否仅包含数字。
#include <ctype.h>
int digits_only(const char *s)
{
while (*s) {
if (isdigit(*s++) == 0) return 0;
}
return 1;
}
Subminiature stylistic sidenote: returns true for the empty string. You might or might not want this behavior.
超小型文体旁注:为空字符串返回 true。您可能想要也可能不想要这种行为。
回答by Programmingcampus.com
#include<stdio.h>
void main()
{
char str[50];
int i,len = 0,count = 0;
clrscr();
printf("enter any string:: ");
scanf("%s",str);
len = strlen(str);
for(i=0;i<len;i++)
{
if(str[i] >= 48 && str[i] <= 57)
{
count++;
}
}
printf("%d outoff %d numbers in a string",count,len);
getch();
}

