2017-03-16 3 views
0
genannt wird

ich wie so ein einfaches Quiz in Linux zu machen versucht:Schlaf() führt auf einmal eher dann, wenn es

#include <stdio.h> 
#include <unistd.h> 

void main() 
{ 
    printf("Simple arithmetic\n"); 
    printf("5 * 7 + 4/2 = ?\n"); 
    sleep(3);      //wait for 3 seconds 
    printf("And the answer is"); 
    for(int i = 5; i > 0; i--){ //wait for another 5 seconds printing a '.' each second 
     sleep(1); 
     printf(" ."); 
    } 
    printf("\n%d!\n", 5*7+4/2);  //reveal the answer 
} 

Problem ist, diese gibt das frist zwei printf ist und wartet dann auf 8 oder so Sekunden, und dann druckt alles andere wie folgt aus:

>> Simple arithmetic 
>> 5 * 7 + 4/2 = ? 
>> // waits for 8 seconds instead of 3 
>> And the answer is..... 
>> 37! // prints everything out with no delay in-between 
Warum passiert das und was kann ich tun, um es zu beheben? Danke für die Hilfe!

+0

Werfen Sie einen Blick auf http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the- format-strin – nnn

+0

'warten' nicht deklariert. 'ich> warte;' -> 'i> 0;' – BLUEPIXY

Antwort

2

flush ist erforderlich, wenn Sie eine sofortige Ausgabe wünschen.

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
void main() 
{ 
     printf("Simple arithmetic\n"); 
     printf("5 * 7 + 4/2 = ?\n"); 
     sleep(3);      //wait for 3 seconds 
     printf("And the answer is"); 
     for(int i = 5; i > 0; i--){ //wait for another 5 seconds printing a '.' each second 
       sleep(1); 
       printf(" ."); 
       fflush(stdout); // this line will do magic 
     } 
     printf("\n%d!\n", 5*7+4/2);  //reveal the answer 
} 
Verwandte Themen