0
#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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    Your string contains characters, not the corresponding digit values. Change `9` to `'9'` and `0` to `'0'`. That way you'll do character comparisons. Alternatively, you can convert the character to the corresponding digit value first, then compare to the ordinary digit values. – Tom Karzes Sep 28 '21 at 03:11

1 Answers1

0

Character symbols of digits are '0', '1', and up to '9'.

The for loop should be interrupted as soon as a non-digit character is encountered.

It is better to use a while loop. Calling strlen within the for loop is redundant and inefficient. For example

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");

You may also use the standard function isdigit declared in the header <ctype.h> instead of explicitly to compare with symbols of digits. For example

#include <ctype.h>

//...

while ( isdigit( ( unsigned char )*p ) ) ++p;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335