Pregunta

I'm sorry about the generic title, but i didn't find anything better. And I'm sorry if the question is stupid but I'm a novice and I could not find anything of use to me.

I have written this code to solve a simple problem: you have a sequence of positive integers terminated by a negative: for every integer you have to print a corresponding amount of * characters and go to a new line.

The code DOES WORK but I can't really understand WHY.

int main()
{
    int d=0,i;
    while (d>=0){
        scanf("%d",&d);
        for (i=0;i<d;i++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}

I did a bit of research and I understand that terminal gives the integer sequence to scanf only when I press return. I thought it would work this way:

  • scanf gets the integer sequence it registers the first one while the others are discarded
  • prints the amount of *s corresponding to the first integer

Instead it seems that scanf reads the first integer, then printf sends it to a buffer then the cycle restarts and scanf gets the second integer and so on. When the last positive integer is reached printf flushes the buffer.

Am I wrong? And if not, why does it work this way?

¿Fue útil?

Solución

scanf() does reads the first integer, then printf sends it to a buffer then the cycle continues and scanf gets the second integer and so on. After a negative integer is reached the rest of stdin is ignored. stdout is flushed with each \n and program ending.

Otros consejos

This should clear your ideas about scanf

http://home.datacomm.ch/t_wolf/tw/c/getting_input.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top