【问题标题】:printf() on the same line as a scanf()printf() 与 scanf() 在同一行
【发布时间】:2013-02-08 18:00:58
【问题描述】:

到目前为止,这是我的代码:

printf("Input:\t   Radius:\tSurface Area:\t Circumference:\t    Volume:\n\n");
scanf("%lg", &diameter);
printf("%lg%lg\t\t%-12lg\t\t%-12lg\t\t%-12lg\n\n", diameter, calcRadius(diameter), calcSurfaceArea(diameter), calcCircumference(diameter), calcVolume(diameter));

我的输出如下所示:

Input:     Radius:      Surface Area:    Circumference:     Volume:

99
9949.5          30775.1                 310.86                  507790

Press any key to continue . . .

我怎样才能让输出看起来像这样:

Input:     Radius:      Surface Area:    Circumference:     Volume:

  99      9949.5          30775.1       310.86             507790

Press any key to continue . . .

简而言之,我意识到在使用 scanf() 并且用户按下回车后, printf() 会自动打印到新行。我怎样才能得到它,这样它就会在用户输入数字的同一行上打印,即使用户按下回车键也是如此。

我应该使用不同的函数来获取输入,还是完全不同的方法?

【问题讨论】:

    标签: c printf scanf


    【解决方案1】:

    您可以使用 termios 库将 STDIN 设置为非规范和非回显模式,并自己开始回显字符,这样就不会打印换行符。此外,如果你想走这条路,你必须使用自己的 scanf 实现:

    http://www.gnu.org/software/libc/manual/html_node/Noncanon-Example.html

    【讨论】:

      【解决方案2】:

      您需要查看 curses 库才能执行此类操作。

      【讨论】:

        【解决方案3】:

        你知道 scanf 会做什么。对于您的程序,您可以在 printf() 中删除打印直径

        printf("Input:\t   Radius:\tSurface Area:\t Circumference:\t    Volume:\n\n");
        scanf("%lg", &diameter);
        printf("\t%lg\t\t%-12lg\t\t%-12lg\t\t%-12lg\n\n", calcRadius(diameter), 
        calcSurfaceArea(diameter), calcCircumference(diameter), calcVolume(diameter));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-08
          • 1970-01-01
          • 2012-06-03
          • 2020-08-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多