Search code examples
cgetcharputchar

Why is putchar() printing out the char with the "%" symbol?


I have the code:

#include <stdio.h>
int main(void) {
    int c;
    c = getchar();
    putchar(c);

    return 0;
}

and after compiling and running, when I input k for example, it prints out k%. Why is it printing out %?

Edit: I tested a few things out and realized that it's the shell (I'm using zsh with oh-my-zsh configuration which is pretty awesome) that's doing that in order to get to a new line. I attached putchar('\n') at the end of the main() function and it doesn't print that out. Thanks for the helpful comments.

(Please let me know the reasons for the downvotes so I could improve my further questions in the future)


Solution

  • A couple of things could be causing that % sign to appear:

    Your program outputs k without a new line, and your shell prompt just looks like this:

    % 
    

    Meaning that you run the program like so:

    % ./a.out
    k //getchar
    k% //putchar + exit + shell prompt
    

    So in short: the % isn't part of the output.

    There is of course the problem with your code triggering UB: the implicit int return type is no longer part of the C standard since C99 and up, and your main function is not quite right, some standard compliant main functions are:

    int main(void);
    int main (int argc, char **argv);
    int main (int argc, char *argv[]);
    

    using () is not the same thing.

    Lastly, you're not returning anything from main, which you should do, just add return 0 at the end.