如何在不转到下一行的情况下在 C 中使用 printf() 和 scanf()? [英] How to use printf() and scanf() in C without going to the next line?

查看:80
本文介绍了如何在不转到下一行的情况下在 C 中使用 printf() 和 scanf()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一行中获取出生日期:

I want to get date of birth in one line:

#include <stdio.h>

int main()
{
    int BirthYear,BirthMonth,BirthDay;
    printf("Please enter your birth date: ");
    scanf("%d",&BirthYear);
    printf("/");
    scanf("%d",&BirthMonth);
    printf("/");
    scanf("%d",&BirthDay);
    return 0;
}

这是我的输出:

Please enter your birth date: YYYY
/MM
/DD

但我想得到这样的东西:

But I want to get something like this:

Please enter your birth date: YYYY/MM/DD

在输出中,它在每次 scanf() 之后转到下一行而不使用 \n.我使用 VS Code 进行 IDM.

In output, it goes to next line after each scanf() without using \n. I use VS Code for IDM.

推荐答案

这里是使用 ansi 控制字符的解决方法.我不会这样做,只是为了表明这是可能的:

Here is a workaround using ansi control characters. I would not do like this, but just to show that it is possible:

#define PREVLINE "\033[F"
#define MSG "Please enter your birth date: "

int main(void) {
    int BirthYear,BirthMonth,BirthDay;
    
    printf(MSG);
    scanf("%d",&BirthYear);
    printf(PREVLINE MSG "%d/", BirthYear);
    scanf("%d",&BirthMonth);
    printf(PREVLINE MSG "%d/%d/", BirthYear, BirthMonth);
    scanf("%d",&BirthDay);
    printf("You entered: %d/%d/%d\n", BirthYear, BirthMonth, BirthDay);
}

请注意,这不可移植.终端需要支持这一点才能工作.AFAIK 没有 100% 可移植的方式来实现这一点.

Please note that this is not portable. The terminal needs to support this in order to work. AFAIK there's no 100% portable way to achieve this.

如果您想真正地做这些事情,那么我建议您查看ncurses 库

If you want to do this stuff for real, then I recommend taking a look at the ncurses library

注意:

始终检查 scanf 的返回值以检测错误.

Always check the return value for scanf to detect errors.

注2:

在每个 printf 语句之后添加 fflush(stdout); 可能是个好主意.

It may be a good idea to add fflush(stdout); after each printf statement.

我今天实际上写了另一个关于 ascii 控制字符的答案.可能很有趣:https://stackoverflow.com/a/64549313/6699433

I actually wrote another answer today about ascii control characters. It might be interesting: https://stackoverflow.com/a/64549313/6699433

这篇关于如何在不转到下一行的情况下在 C 中使用 printf() 和 scanf()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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