“cls”未运行。屏幕不会被擦除

问题描述 投票:0回答:1
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

void ViewHP(int health)
{
    printf("HP = ");

    for (int i = 0; i < health; i++)
    {
        printf(" ♥ ");
    }

    printf("\n");
}

int main()
{
    while (1)
    {
        ViewHP(5);
        system("cls");
    }
}

“cls”未运行。我写了

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
,代码正常。 执行后,cls 不起作用。代码中似乎没有错误,执行本身也不起作用。即使使用cls,屏幕也不会被擦除,但仍然会打印出来。尽管我搜索了很多,但情况并非如此,所以我留下一个问题。

c windows cls
1个回答
0
投票

就像 SO 社区在评论中指出的那样,

while()
循环永远不会暂停,这样您就可以确保清屏方法(
system("cls")
)实际上有效。以下代码通过
main()
中的逻辑解决了该问题。 。 .

。 。 。还引入了一个替代的、基于 MS Windows 的(根据您的代码)

clrscr()
函数。
clrscr()
here提到的东西的混合体,但非常原始——只需向控制台/终端写入足够的换行符(
\n
)以匹配控制台/终端高度。

因为它很原始,所以它应该在未来的许多年里都可以工作——跨控制台和终端——无论随着时间的推移哪一个占主导地位。这是因为足够的换行符 (

\n
) 字符应该会导致滚动和屏幕清除(通过将先前的行向上推),直到未来某个奇怪的新的、不可预测的一天。

此代码是我在几分钟前 100% 编译和测试的:

#include <stdio.h> 
#include <conio.h> /* _getch() */
#include <windows.h>

int clrscr(void)
{
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    int i, bSuccess = 0;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    COORD coordScreen = { 0, 0 };    /* home for the cursor */

    if(hStdOut)
    {
        if (GetConsoleScreenBufferInfo(hStdOut, &csbi))
        {
            for(i=0; i < csbi.dwSize.Y; i++) /* for() console window height . . . */
                putchar('\n');  /* . . . print newlines to clear the screen. */
            /* Home the cursor just like cls does: */
            if(SetConsoleCursorPosition(hStdOut, coordScreen)) 
                bSuccess = 1;
        }
    }
    return bSuccess;
}

void ViewHP(int health)
{
    int i;

    printf("HP = ");
    for (i = 0; i < health; i++)
    {
        printf(" ♥ ");
    }
    printf("\n");
}


int main()
{
    int done=0;
    while (!done)
    {
        ViewHP(1000);
        system("pause"); /* pause to see results of screen fill. */
        clrscr();  /* Can still use system("cls") if you prefer. */
        /* Pause again to ensure clear screen is working correctly: */
        if(_getch() == 27) /* ESC key quits . . . */
            done = 1;
    }
    return (0);
}
© www.soinside.com 2019 - 2024. All rights reserved.