taemm
taemm

Reputation: 19

conditional operator usage using printf in C

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;
}

Upvotes: 1

Views: 103

Answers (1)

chqrlie
chqrlie

Reputation: 144969

% 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;
}

Upvotes: 2

Related Questions