Search code examples
cvalidationuser-inputfgets

single-character user input and fgets


Noob question here, but I am teaching myself C and trying to figure out user input in the safe, correct way (for reference this is the morse code array exercise in the GNU C Programming Tutorial at 10.6 (58-59) and 15.5.5 (107)).

My desired program flow is:

  • prompt user for a single numeral
  • get user input
  • validate user input
  • if valid print correct array item

The problem is that if the user simply enters a hard return, the array reading function reads and prints from my_array[0]. I can't figure out how to cause a return to fail the validation.

in main:

if (get_line (digit_input, sizeof (digit_input), stdin) != NULL ) {
  if (validate (digit_input) == 0) {
    digit = atoi (digit_input);
    printf("\nThe Morse code for %d is: ", digit);
    morse(digit);
}

get_line and validate functions:

char *get_line(char *s, size_t n, FILE *f) {
  unsigned int last;
  char *p = fgets (s, n, f);

  if (p != NULL) {
    last = (strlen(s) - 1);
    if (s[last] == '\n') s[last] = '\0';
  }
  return p;
}

int validate(char *a) { 
  unsigned x;

  for (x = 0; x < strlen(a); x++)
    if ( !isdigit(a[x]) || (a[1] != '\0' )) return -1;

  return 0;
}

How I can invalidate blank input? (i.e, if the string reads \n\0?) And why is a no-character (i.e., \n) input made into a 0 and passed to the array reading function?

Thanks everybody for the help!


Solution

  • Add the following test in the beggining of validate function:

    if (strlen(a) == 0) return -1;
    

    So, blank input will be invalidated.