1

I need to consider the user input character is white space or not. The program works well when I type in a blank space, * is printed out successfully. But when I type a character that is not white space, I can't get %. Instead the character that I entered is just printed out.

Is there a problem with my conditional operator code?

This is my code:

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

int main() {
    char character;
    printf("Press any single key\n");
    character = getchar();
    
    (isspace(character) > 0) ? printf("*") : printf("%");

    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
taemm
  • 19
  • 1
  • 2
    `printf("%")` should be `printf("%%")`. A percent character on its own needs to be "escaped", because a complete format instruction such as `"%d"` is expected. – Weather Vane Oct 01 '22 at 13:23
  • 1
    Fwiw printf(isspace(character)?”*”:”%%”); would work also. – Jeremy Friesner Oct 01 '22 at 13:25
  • `printf("%c", isspace(character) ? '*' : '%' )` – dimich Oct 01 '22 at 13:50
  • Does this answer your question? [How to escape the % (percent) sign in C's printf](https://stackoverflow.com/questions/1860159/how-to-escape-the-percent-sign-in-cs-printf) – phuclv Oct 01 '22 at 22:40

1 Answers1

2

% is a special character in a printf format string. To output a % characters, you can:

  • either use printf("%%");
  • or use putchar('%');

Also note these problems:

  • character should be defined with type int to reliably store all return values of the function getchar(), including the special negative value EOF.

  • isspace() is defined for values of type unsigned char and the special value EOF returned by getchar(), do not pass a char value. Instead, define character as an int and pass that.

  • isspace() does not necessarily return a positive value for whitespace characters, you should just test if the return value is non zero, which in C can be written:

      if (isspace(character)) {
          ...
    

Here is a modified version:

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

int main() {
    int c;

    printf("Press any single key\n");
    c = getchar();
    
    if (isspace(c)) {
        putchar('*');
    } else {
        putchar('%');
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189