开发者

Magic of scanf() function?

Why run this code and print whole string?

#include <stdio.h>

void main()
{
    int a;
    while(a!='q')
    {
        scanf("%c",&a);
        printf("%c",a);
    }
}

Enter string except q, 开发者_开发问答and finally press enter key. Only now your string will print on the screen. Why?


The problem here is not with scanf, it is with your printf call.

Printf buffers output until a new line is reached, so the program will not display anything until you printf("\n");. (Which also happens when someone presses enter, you output their return to the screen which causes the buffer to flush.)

If you don't want to break up your output with printf("\n"), then you can use fflush(stdout) to manually flush the buffer without printing anything, like this:

int a;
while(a!='q')
{
    scanf("%c",&a);
    printf("%c",a);
    fflush(stdout);
}


Well for starters, that code won't compile - print is not a function in C, printf is one one you're looking for.

As for what I think you are asking, I don't know why you would want to print every character you read until you read q; it seems kinda pointless.


At first you need to define a to be of char type:

char a;

When you hit enter, the while loop will run for so many times as many characters you have inputed.Try this to see what is happening:

char a = 0;
int i = 0;
while(a!='q')
{
    scanf("%c",&a);
    printf("%d:%c",i++,a);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜