Search code examples
cfgets

Scanning white space with fgets()


I'm running user input through a series of functions provided by the ctype.h library, but scanf doesn't work for white space.

Since I can't use scanf for whitespace I believe fgets() should be what I'm looking for, but am unsure about the last parameter I would use for it. Any advice would be appreciated!

#include <stdio.h>
#include <ctype.h>

int main(void) {
  char a;

  puts("Enter a character:");

  //scanf("%s", &a);
  fgets(a, 1, ??);


  printf("isblank('%c')  = %d \n", a ,isblank(a)); 
  printf("isdigit('%c')  = %d \n", a ,isdigit(a));
  printf("isalpha('%c')  = %d \n", a ,isalpha(a));
  printf("isalnum('%c')  = %d \n", a ,isalnum(a));
  printf("isxdigit('%c') = %d \n", a ,isxdigit(a));
  printf("islower('%c')  = %d \n", a ,islower(a));
  printf("isupper('%c')  = %d \n", a ,isupper(a));
  printf("tolower('%c')  = %d \n", a ,tolower(a));
  printf("toupper('%c')  = %d \n", a ,toupper(a));
  printf("isspace('%c')  = %d \n", a ,isspace(a));
  printf("iscntrl('%c')  = %d \n", a ,iscntrl(a));
  printf("ispunct('%c')  = %d \n", a ,ispunct(a));
  printf("isprint('%c')  = %d \n", a ,isprint(a));
  printf("isgraph('%c')  = %d \n", a ,isgraph(a));

  return 0;
}

Output should look like this

Enter a character:
 C
isblank('C')  = 0 
isdigit('C')  = 0 
isalpha('C')  = 1024 
isalnum('C')  = 8 
isxdigit('C') = 4096 
islower('C')  = 0 
isupper('C')  = 256 
tolower('C')  = 99 
toupper('C')  = 67 
isspace('C')  = 0 
iscntrl('C')  = 0 
ispunct('C')  = 0 
isprint('C')  = 16384 
isgraph('C')  = 32768

Program should intake a single character and convert it to integer through a series of functions.


Solution

  • The first argument to fgets() needs to be a buffer that can hold the entire line of input.

    int main(void) {
      char a;
      char line[100];
      puts("Enter a character:");
    
      fgets(line, sizeof line, stdin);
      a = line[0];