【问题标题】:C code to out yes if string contains all numbers, and no if it does contain something other than numbers [duplicate]如果字符串包含所有数字,则C代码输出是,如果它确实包含数字以外的其他内容,则为否[重复]
【发布时间】:2021-11-20 02:49:15
【问题描述】:
#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("Yes\n");
   else if (hello == 1)printf("No\n");

   return 0;
}

【问题讨论】:

  • 您的字符串包含字符,而不是相应的数字值。将9 更改为'9' 并将0 更改为'0'。这样你就可以进行字符比较。或者,您可以先将字符转换为对应的数字值,然后与普通数字值进行比较。

标签: c loops char c-strings digits


【解决方案1】:

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

一旦遇到非数字字符就应该中断for循环。

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

const char *p = input;

while ( '0' <= *p && *p <= '9' ) ++p;

hello = *p != '\0';

if (hello == 0) printf("Yes\n");
else if (hello == 1)printf("No\n");

您也可以使用在标头&lt;ctype.h&gt; 中声明的标准函数isdigit,而不是显式地与数字符号进行比较。例如

#include <ctype.h>

//...

while ( isdigit( ( unsigned char )*p ) ) ++p;

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 2019-03-15
    • 2018-04-02
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2016-04-09
    相关资源
    最近更新 更多