Search code examples
cprintfgetchar

How do I print this in C?


Hi I'm relatively new to programming so please bear with me.

I would like to make a program that takes the input bcdefghijklmnopqrstuvwxy and outputs

else if (c == 'x')
     ++nx;

where x is a letter of the input, and where the output is repeated for each letter of the input.

This is what I have written so far:

#include <stdio.h>

main() {

    int c;

    while((c = getchar()) != EOF) {
        printf("else if (c == '%d')\n", c);
        printf("\t++n%d;\n", c);
    }

    return 0;
}

Instead of returning the output I want, the output is

else if (c == '98')
    ++n98;
else if (c == '99')
    ++n99;
else if (c == '100')
    ++n100;
else if (c == '101')
    ++n101;
else if (c == '102')
    ++n102;
...

Why is c not working as a variable?

Thanks so much for your help!


Solution

  • When writing in C and printing a string pointed by format to stdout you'll need to make sure you're using the right format specifiers. This will ensure that your argument is formatted correctly and inserted into the resulting string as you would expect.

    In your case, you need to use %c. However, you have %d currently, which is the equivalent to %i for integers. You can google more on format specifiers to learn more about other options as well.

    Here's an interesting read on the subject:

    http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output