函数 printf() 打印退格问题 [英] Function printf() to print backspace problem

查看:137
本文介绍了函数 printf() 打印退格问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个程序,它们得到不同的结果,但我不明白为什么.这是第一个:

There are two programs and they get different results, but I don't understand why. Here is the first:

int main()
{
    printf("12345");
    fflush(stdout);
    printf("\b\b");
    fflush(stdout);
    return 0;
}

结果是:123.然后第二个:

The result is: 123. Then the second:

int main()
{
    printf("12345");
    fflush(stdout);
    sleep(1);
    printf("\b\b");
    fflush(stdout);
    return 0;
}

但结果是:12345.

为什么当我期望123"结果时,睡眠调用会使第二个结果不同?代码在 CLion 中运行.如果重要的话,我的操作系统是 macOS.

Why does the sleep call make the second result different when I expect a "123" result? The code was running in the CLion. and My OS is macOS, if it matters.

推荐答案

根据终端的不同,'\b' 可能会擦除"一个字符或仅将光标向左移动.要获得万无一失的解决方案,请使用:

Depending on the Terminal, '\b' might "erase" a character or only move the cursor to the left. To have a foolproof solution, use:

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

int main(void)
{
    printf("12345");
    fflush(stdout);
    sleep(1);
    printf("\b\b  \b\b");
    fflush(stdout);
}

这篇关于函数 printf() 打印退格问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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