C代码输出"是",如果字符串包含所有数字,如果字符串不包含数字,则输出"否".&


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char input[50];
int i, hello = 0; // Wish to out Yes if "9999" is input. But why does it not happen?

scanf("%s", input);

for (i = 0; i<strlen(input); i++){
if (input[i]>9 || input[i]<0){
hello = 1;}
}

if (hello == 0) printf("Yesn");
else if (hello == 1)printf("Non");
return 0;
}

数字的字符符号为'0','1',直到'9'

一旦遇到非数字字符,应立即中断for循环。

最好使用while循环。在for循环中调用strlen是多余且低效的。例如

const char *p = input;
while ( '0' <= *p && *p <= '9' ) ++p;
hello = *p != '';
if (hello == 0) printf("Yesn");
else if (hello == 1)printf("Non");

您也可以使用标头<ctype.h>中声明的标准函数isdigit来代替显式地与数字符号进行比较。例如

#include <ctype.h>
//...
while ( isdigit( ( unsigned char )*p ) ) ++p;

最新更新