c - 防止用户跳转到 C 中带有 "enter button"的另一行

标签 c printf scanf newline

  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();

问题是,一旦我实际输入一个值,程序就会跳过输入的值,我需要在将其存储在变量中之前再次实际输入它。

这就是它的整体样子,“防止换行”函数和第一个读取用户输入的“aroma”的函数

  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);

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

最佳答案

您只能通过 scanf()printf() 执行大多数简单的输入/输出。

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

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

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

关于c - 防止用户跳转到 C 中带有 "enter button"的另一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59911947/

相关文章:

c++ sprintf 函数和 fstream 来创建/检查文本文件

c - 尝试使用 scanf 中的数据时出现段错误?

C - 使用 sscanf 忽略空格

android - 如何将现有的 make 文件与 Android NDK 合并

cuda - thrust::device_reference 不能和 printf 一起使用?

java - 如何在一条语句中打印多个类实例? java

c - For循环在C中崩溃

c - 如何阻止我的程序在保存字符之前跳过它们

c - 如何在C中获取终端上任何命令的执行文件目录?

c - C语言中SafeStr的使用