簡體   English   中英

C while 循環使用 scanf 在輸入超過 1 個字符時打印兩次

[英]C while loop using scanf prints twice when entering more than 1 char of input

我正在嘗試從 C 中的標准輸入讀取輸入,如果輸入的字符是除“輸入”之外的任何鍵,程序將執行一些任務。 我正在使用一個while循環,當用戶只輸入1個字符時它可以正常工作,但是當他們輸入更多時會打印一行兩次(輸入超過1個字符很好,程序應該為每個生成一個新數字 - - 就像用戶輸入“aaa”一樣,它會生成 3 個新數字。)

所以這是理想的 output 在輸入類似 '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);

}

是什么原因造成的,我該如何解決?

在你的循環中試試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM