for loop brackets in c

╄→гoц情女王★ 提交于 2021-02-05 06:23:24

问题


I write a program to print integer values using for loop and after printing, the program should wait one second, after that those integers are overwrite with double space character in other words the purpose of the program is to erase those integer after wait for one second.

This the program:

#include <stdio.h>
#include <time.h>

int main (void) {
   int i;

   for(i=1;i<=5;i++){
       printf("%d ",i);
   }

   for(;clock () < CLOCKS_PER_SEC;){} /*wait for one second*/

   printf("\r");     /*move to the beginning of the line*/ 
   for(i=1;i<=5;i++){
      printf("  ");   /*overwriting the integers*/
   }
   printf("\n");

   return 0;
}

The problem is in the wait loop loop brackets `for(;clock () < CLOCKS_PER_SEC;){}' when i remove those brackets the program work properly. but if the for loop with brackets. the program doesn't work,I mean the program still runs but it overwrite the integer instead of showing those integers first.

please someone explain what happen?


回答1:


You aren't flushing stdout (the stream that printf writes to) yourself so it doesn't happen until the '\r' is written, and then you immediately clear it.

If you remove the {}, then your loop is equivalent to

for(;clock () < CLOCKS_PER_SEC;)
    printf("\r");

which writes a bunch of \r, the first of which flushes the output and the rest of which are redundant. After the loop completes, you clear the line, working as you want it to.

You should call fflush(stdout) after printing the numbers. Or you could move the printf("\r") so it comes before the wait loop (the difference being where the cursor ends up).

Your loop is problematic, as there's no guarantee that clock() starts at 0, and it won't on many systems, and you shouldn't spin like that ... it slows down other programs running on your system. You could just use sleep(1), although it's not very accurate.




回答2:


When you remove the brackets, the printf("\r") statement becomes the body of the for loop, logically equivalent to this:

for(;clock () < CLOCKS_PER_SEC;) {printf("\r");}

So the integers get overwritten right away instead of after the end of the delay period.

Of course, the real question is why you are using a busy-loop for a delay rather than just calling sleep(1), which is much more efficient (i.e. it won't pin your CPU at 100% during the delay period)




回答3:


I suspect somehow the output buffer is being flushed differently between the two cases. You could check this by manually flushing the buffer using fflush(stdout) before the problematic loop.

Also note that the {} aren't mandatory in C, for single-line statements within the loop.




回答4:


Here is the code you might want:

#include <stdio.h>

int main(int argc, char * argv[]) {
    int seconds = 10;

    while(seconds>0) {
        printf("%10d", --seconds);
        fflush(stdout);
        sleep(1);
        printf("\r");
    }
    printf("%10s\n", "time up!");

    return 0;
}

(Since you ask about what fflush() acturally is, here is a little explanation base on my understanding)

It's all about io cache, 1 reason cache exists is: read/write memory could be over 1000 times quicker than hard disk.

So program should try do reduce the frequence of read/write hard disk, and use memory instead, but need a proper tradeoff for the user experience and io delay.

e.g

  • When read a file by lines, it could read 2kb or so at once instead a single line, then could read from the memory cache,
  • When write to console, the program might choose to write to the memory cache until meet a \n or \t char, and some other case.

fflush(FILE * file), is a function from stdio.h, it flush the cache of specified FILE. In your case, the file is stdout(standard output), which print to your console. When you use printf() to print a single number, it might write to cache of stdout, so you didn't see it in console, but calling fflush(stdout) flush out the cache to your console.





回答5:


On the first 'for' loop you are printing values using printf. Here 'printf' uses 'stdout' which is a buffered output- meaning output will not be printed unless '\n' is provided or buffer full. so you can either uses flush(stdout) after the first loop or uses fprintf(stderr, "") to print to standard error which is not a buffered output.



来源:https://stackoverflow.com/questions/26435811/for-loop-brackets-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!