【问题标题】:C while loop using scanf prints twice when entering more than 1 char of input输入超过 1 个字符的输入时,使用 scanf 的 C while 循环打印两次
【发布时间】:2021-11-28 18:19:24
【问题描述】:

我正在尝试从 C 中的标准输入读取输入,如果输入的字符是“输入”以外的任何键,程序将执行一些任务。我正在使用一个while循环,当用户只输入1个字符时它可以正常工作,但是当他们输入更多时会打印一行两次(输入超过1个字符很好,程序应该为每个生成一个新数字 - - 就像用户输入“aaa”一样,它会生成 3 个新数字。)

所以这是输入“eeee”之类的内容后的理想输出(当您只输入一个字符时它工作正常):

CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):

但这是当您输入“eeee”时实际发生的情况:

enter any key for call (q to quit, no enter): CallList: I22 U55 U52 L1
enter any key for call (q to quit, no enter):

这是我的代码的一部分(最小可复制版本):

#include <stdio.h>
#include <stdlib.h>
int main(void){

system("clear");
  printf ("CallList: \n");
  printf("enter any key for call (q to quit, no enter): ");
char c;
  scanf(" %c", &c);
  system("clear");

char quit = 'q';
  int random;
  srand(1063);

  while (c != quit){

    if (c != '\n') {
      random = rand() % 75 + 1;
      // does a few functions here, they don't print anything and don't use stdin
     }
    printf ("CallList: ");
    // prints the call list here
    printf("\n");
    printf("enter any key for call (q to quit, no enter): ");
    scanf(" %c", &c);
    system("clear");
    }
printf("Goodbye! \n");
  exit(0);

}

这是什么原因造成的,我该如何解决?

【问题讨论】:

  • 考虑阅读Dragon book的一些章节,关于parsingrecursive descent parser,如果允许,使用GNU bison。如果允许,将GCC 编译器用作gcc -Wall -Wextra -gGDB 调试器
  • 终端的行为是特定于操作系统的。在 Linux 上,请参阅 termios(3)pty(7)。如果允许,请使用GNU readline
  • @BasileStarynkevitch 感谢您的评论!我使用了 gdb 的在线调试器,它在运行时什么也没说,但是当我输入 q(退出 0)时,它说: 0x00007ffff7ed9142 in __GI___libc_read (fd=0, buf=0x5555555596b0, nbytes=1024) at ../sysdeps/unix /sysv/linux/read.c:26 26 ../sysdeps/unix/sysv/linux/read.c:没有这样的文件或目录。”我不知道这是什么意思
  • 您可能需要花费 来阅读有关 Linux 编程的书籍。这些书印在纸上。花几个小时阅读 GCC 和 GDB 的文档
  • scanf函数可能有问题,考虑用getline代替。

标签: c while-loop stdin


【解决方案1】:

在你的循环中试试这个:

    while (c != quit){
 
        if (c != '\n') {
            random = rand() % 75 + 1;
            //here you can add things to your calllist
            c = getchar();
        }
        else {
            printf ("CallList: ");
            // prints the call list here
            printf("\n");
            printf("enter any key for call (q to quit, no enter): ");
 
            c = getchar();
            system("clear");
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 1970-01-01
    • 2016-07-22
    相关资源
    最近更新 更多