Search code examples
cinputalphanumeric

storing alphanumerics as an unknown number of digits in C


I'm trying to read 4 user inputs that can either be one digit, two digits, or a letter. I've tried using %c, but that can't contain any two digit numbers. I've also tried %d, but that reads all letters as 0. Is there anything that can cover all the bases?


Solution

  • Read a line and store it as a string. Then you can analyze what you got.

    Simple example:

      size_t n = 2;
      char *str;
      str = malloc (n + 1);
      getline (&str, &n, stdin);
    
      if (str[0]>='0'&& str[0]<='9')
        if (str[1]>='0' && str[1]<='9')
          printf("Two digits\n");
        else
          printf("One digit\n");
    

    Note that this is very naive, and contains almost no error detection, but it gives an idea for how to do it.