用于c中的循环括号 [英] for loop brackets in c

查看:48
本文介绍了用于c中的循环括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个程序,使用for循环打印整数值,打印后,程序应等待一秒钟,之后这些整数将被双倍空格字符覆盖,换句话说,该程序的目的是在等待后擦除那些整数一秒钟.

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.

此程序:

#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;
}

问题出在等待循环循环括号"for(; clock()< CLOCKS_PER_SEC;){}"删除那些括号,程序可以正常工作.但是如果for循环带有括号.该程序不起作用,我的意思是该程序仍在运行,但是它会覆盖整数而不是首先显示这些整数.

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?

推荐答案

您不会自己刷新stdout(printf写入的流),因此只有在写入'\ r'之后,它才会发生立即清除它.

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");

编写一堆 \ 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.

打印数字后,您应该拨打 fflush(stdout).或者,您可以将printf("\ r")移到等待循环之前(区别是光标结束的地方).

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).

您的循环是有问题的,因为不能保证clock()从0开始,并且在许多系统上也不会,并且您不应该那样旋转...这会减慢系统上运行的其他程序的速度.您可以使用sleep(1),尽管它不是很准确.

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.

这篇关于用于c中的循环括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆