开发者

C Prints One Char More Without Value

I am trying to print the ASCII values of 3 char-type characters. When I input the first char it doesn't print the value of the char. After the first char it starts 开发者_StackOverflow中文版to give the value.

#include <stdio.h>
int main()  {
    char ch;
    int t;
    while(t < 3){
        scanf("%c\n", &ch);
        printf("%c - %d\n", ch,ch);
        t++;
    }
}

http://i54.tinypic.com/2mdqb7d.png


Variable t is not automatically initialized to 0 by compiler. So You need to initialize t with 0. If printf doesn't print immediately it means the data is buffered. If you want to see immediatley you may consider flushing stdout right after printf.


I saw this several times, and don't know the root cause, but solution that works is:

scanf("\n%c", &ch);

It probably has something to do with buffered end of line character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜