Search code examples
cinputasciigetchar

Strange 10 value gets printed when I print inputed characters by their ASCII decimal code


#include <stdio.h>
#include <stdlib.h>

int main()
{
    int end;

    while(( end = getchar() ) != EOF ){
        printf("%d\n",end);
    }
    system("pause");
    return 0;
}

I want to print the ASCII codes of characters with this code but whenever I run the code after it gets the char from me it prints its ASCII equivalent with decimal 10. For example if I run the code and pass "a", it will print 97 and 10. Why does it print 10, this happens with all other characters too. Thank you for answers and as a followup question when I add a counter after I input a character counter's value increases by two, why does this happen

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int end;
    int count=0;
    while(( end = getchar() ) != EOF ){
        printf("%d\n",end);
        count++;
        printf("counter is now %d\n",count);
    }
    system("pause");
    return 0;
}

Solution

  • As stated you are printing the ASCII decimal codes for 'a' and '\n' respectively, this is because, in your code, getchar reads all the characters in the stdin buffer, including the newline character which is present because you press Enter.

    You can avoid this by simply making it be ignored by your condition:

    while((end = getchar()) != EOF && end != '\n'){
        printf("%d\n", end);
    }
    

    Disclaimer: David Ranieri added a comment with the exact same solution as I was writing my answer (which he kindly deleted) so credit to him as well.


    Regarding your comment question and the question edit:

    If you don't want the '\n' to interrupt your parsing cycle, you can simply place the condition inside it.

    while((end = getchar()) != EOF){
        if(end != '\n'){ //now as '\n' is ignored, the counter increases by one
           printf("%d\n", end);
           count++; 
           printf("counter is now %d\n",count);
        }
    }
    

    The reason why the counter is increased by two is, again, because two characters are parsed, whatever character you input and the newline character. As you can see in the sample, if you ignore the '\n', the counter will only increase by one, provided that you only enter one character at a time.