条件退格。我想在printf中使用条件退格

时间:2014-12-10 18:36:35

标签: c

在程序中,如果条件成立,我想删除一个单词。 有没有办法做到这一点。 我正在考虑使用转义序列。

/* program to print number into words.  */ 

# include <stdio.h>
void main()
{
    char *single_numbers[10]={" ","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
    char *tens_numbers[9]={"Twenty","Thirty","Fourty","Fifty","Sixty","Seventy","Eighty","Ninety"};
    char *teens[9]={"Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    int number,thousands,hundreds,tens,units,temp;
    printf("enter the number");
    scanf("%d",&number);
    if(number>9999)
    {
        printf("please enter a number between 0-9999");
    }else
    {
        thousands=number/1000;
        hundreds=(number%1000)/100;
        temp=(number%100);
        tens=temp/10;
        units=number%10;
        if(temp>=20)
            printf("%s thousand %s hundred %s %s only",
                    single_numbers[thousands],
                    single_numbers[hundreds],
                    tens_numbers[tens-2],
                    single_numbers[units]);
        else
            printf("%s thousand %s hundred %s only ",
                    single_numbers[thousands],
                    single_numbers[hundreds],
                    teens[temp-11]);
    }
}

1 个答案:

答案 0 :(得分:2)

是的,可以使用退格('\b')来覆盖已经打印到屏幕上的内容,但这并不是您通常使用的技术。

不要使用退格符覆盖已经打印的内容,而是修改代码以仅打印所需的部分。这是一个很好的起点,但您需要修改它以涵盖1000,0和1001等情况。

    if (thousands > 0)
        printf("%s thousand ", single_numbers[thousands]);
    if (hundreds > 0)
        printf("%s hundred ", single_numbers[hundred]);
    if (temp >= 20)
        printf("%s %s only\n", tens_numbers[tens-2], single_numbers[units]);
    else
        printf("%s only\n", teens[temp-11]);

实现目标的另一种方法是使用sprintf()打印到缓冲区,并有选择地截断缓冲区以删除书写字符。但是考虑一下它是多么低效 - 为什么打印然后擦除,你可以完全跳过打印步骤?