为什么 system(“cls”) 在 Windows 上对我不起作用?

Why doesn't system("cls") work for me on windows?

提问人:Rick Mortie 提问时间:11/1/2023 更新时间:11/1/2023 访问量:68

问:

我一直在尝试让我的屏幕每秒刷新一次,但我不明白为什么它不起作用。 倒计时有效,但我想只显示最后一个“printf”并删除所有其他“printf”。 顺便说一句,我在窗口上,而不是在 linux 或 Mac 上

这是我试图做的:

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

int main() {
    int décompte;
    décompte = 120;
    time_t debut, maintenant;
    int tempsrestant;

    time(&debut);
    while(1){
        time(&maintenant);
        tempsrestant = décompte - (maintenant - debut);
        if(tempsrestant == 0){
            printf("vous perdez une de vos trois vies\n"),
            sleep(2);
            break;
        }
        else if(tempsrestant>0){
            printf(" tempsrestant : %d sec",tempsrestant);
            sleep(1);
            system("cls");
        }
    }

    return 0;
}
C Windows 控制台 刷新

评论

1赞 Ted Lyngmo 11/1/2023
您是否检查了 的返回值?您可能没有在 CMD.EXE 控制台中运行它,而是在其他地方运行它,例如在 WSL 中,那里不存在。system()cls
1赞 ikegami 11/1/2023
为了支持 Ted,.与泰德相反,.这是某种像 Cygwin、MSYS 或 MSYS2 这样的 unix 仿真环境吗?这些 unix 仿真模拟 unix,因此使用 instead 而不是执行传递给 的 shell 命令。( 是内置的。#include <unistd.h>#include <windows.h>shcmdsystemclscmd
0赞 chux - Reinstate Monica 11/1/2023
@Rick Mortie,尝试:在之后和之前,添加 .printf(...),sleep()fflush(stdout);
0赞 chux - Reinstate Monica 11/1/2023
@Rick莫蒂,“为什么它不起作用。 值得更多。看到了什么?
0赞 ikegami 11/1/2023
@chux - 恢复莫妮卡,好电话,但他们说文本是输出的(“倒计时有效”)。也许冲洗 stdout?不起作用的是屏幕没有被清除(“但我想只显示最后一个”printf“并删除所有其他”printf“)。fflushsystemsystem("cls")

答:

2赞 ikegami 11/1/2023 #1

您同时包含特定于 unix 的头文件 (unistd.h) 和特定于 Windows 的头文件 (windows.h),因此我猜您是在 Unix 仿真环境中运行,例如 Cygwin、MSYS 和 MSYS2 提供的环境。

作为 unix 仿真,它们使用 而不是 to 执行传递给 的 shell 命令。由于是内置的,这是行不通的。shcmdsystemclscmd

执行可能会起作用。
执行会起作用。
clearcmd /c cls

最后,由于您在 unix 仿真中运行,因此以下操作也可能有效:

printf( "\x1B[H\x1B[2J\x1B[3J" );
fflush( stdout );

评论

1赞 chqrlie 11/2/2023
您还可以建议一种更简单的方法:删除呼叫。printf(" tempsrestant : %3d sec\r", tempsrestant); fflush(stdout);system("cls")