【问题标题】:prevent user from jumping to another line with "enter button" in C防止用户在 C 中使用“输入按钮”跳转到另一行
【发布时间】:2020-01-25 17:57:11
【问题描述】:
  printf(" -----------------------------------\n");
  printf("|   *** E - Liquid Calculator ***   |\n");
  printf(" -----------------------------------\n");
  printf("| Zutaten                           |\n");
  printf(" -----------------------------------\n");
  printf("| Aroma:     %%   Nikotin:     mg/ml |\n");
  printf("| Nikotinshot:     mg/ml            |\n");
  printf("| In total:      ml                 |\n");
  printf(" -----------------------------------\n");
  printf("| Ergebnis                          |\n");
  printf(" -----------------------------------\n");
  printf("| Aroma:      ml   Nikotin:     ml  |\n");
  printf("| Base:       ml                    |\n");
  printf(" -----------------------------------\n");

我创建了一个小项目,我希望用户在表格中输入 4 个值,然后计算成分。但是,如果用户在实际输入值之前按下“回车”,光标只会跳到新行,然后破坏整个程序的布局。

我尝试了以下代码来防止任何意外的“换行符/输入”

do   
  {
    POSITION (6,10);
    scanf("%c", &spacebar);
    if (spacebar == '\n')
    {
      POSITION (18,0);
      printf("Eingabe erfordelich!\n");
    }
  } while (spacebar == '\n');
  clearBuffer();

问题在于,一旦我实际输入了一个值,程序就会跳过输入的值,我需要第二次实际输入它,然后才能将它存储在变量中。

这就是它的样子,“防止换行”功能和第一个读取用户输入“香气”的功能

  do   //prevent the user from pressing enter before actually typing a number
  {
    POSITION (6,10);
    scanf("%c", &spacebar);
    if (spacebar == '\n')
    {
      POSITION (18,0);
      printf("Eingabe erfordelich!\n");
    }
  } while (spacebar == '\n');
  clearBuffer();
  POSITION (18,0);
  CLEAR_LINE;


  do
  {
    POSITION (6,10);
    Scan_Erg = scanf("%f", &Aroma);
    clearBuffer();
    if (Scan_Erg == 0)
    {
      POSITION (16,0);
      FORECOLOR_RED;
      printf("Please only enter numbers!");
      FORECOLOR_YELLOW;
      POSITION (6,14);
      CLEAR_LINE;
      POSITION (6,10);
      printf("    %%   Nikotin:     mg/ml |");
    }
    else
    {
      POSITION (6,10);
      CLEAR_LINE;
      POSITION (6,10);
      printf("%4.1f%%   Nikotin:     mg/ml |", Aroma);
    }
  } while (Scan_Erg == 0);

有没有人知道,当没有输入值时,如何阻止输入只是换行符? 任何建议或帮助将不胜感激。 我是编程新手 :-)

【问题讨论】:

    标签: c printf scanf newline


    【解决方案1】:

    您只能通过scanf()printf() 进行最简单的输入/输出。

    您可以构建自己的系统来读取用户输入。

    但正如您所怀疑的,这个问题并不新鲜,一些聪明人提供了一个广泛使用的解决方案:curses 库。

    根据您的开发和/或目标系统,您可能希望搜索ncursespdcurses 及其文档。也会有一些教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多