tags:

views:

130

answers:

3

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?

+3  A: 

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);
}
SoapBox
It's printf, not print.
iconiK
Fixed it, I had copied the typo from the original question.
SoapBox
@SoapBox, might want to edit and restyle the code in the question again. Please?
iconiK
A: 

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.

iconiK
or like homework
Dan McGrath
A: 

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);
}
kgiannakakis
its also possible with int yar(Friend)
Govind KamalaPrakash Malviya