簡體   English   中英

關於 scanf() 的奇怪跳過

[英]Strange skipping concerning scanf()

我一直在嘗試使用鏈表做一些事情,主要是因為我想找到一種方法來確定由用戶輸入確定的序列的長度。 問題是

終端輸出

[filip@filip PointerCheck]$ ./PointerCheck.o 
Enter number to populate the list..
1 2 3
c
Enter number to populate the list..
Printing...
1 2 3 
3

為什么跳過列表的第二個群體?

我嘗試了多種方法,我相信問題出在 while 循環條件中的某個地方,與scanf();有關scanf();
列表函數應該可以正常工作,因為來自add_to_list()的單獨調用確實在列表中插入了一個整數,並且print_list()打印了所有這些。 所以我猜,一定是while循環,特別是scanf();

C代碼

void user_input_list(void) {
  int *input = NULL;
  input = (int *) malloc(sizeof(int));
  printf("Enter number to populate the list..\n");
  while (scanf("%d", input)) {
    add_to_list(*input, 1);
  }
}

int main(int argc, char const *argv[]) {
  int i = 0;
  struct node *ptr = NULL;

  user_input_list();

  user_input_list();

  print_list();
  printf("%d\n", lenght_list());

  return 0;
}

這是整個文件,live [link]pastebin

看起來您正在輸入一個非數字字符來表示輸入結束。 但是, scanf()遇到的第一個不匹配字符留在輸入流中。 因此,您需要在嘗試再次讀取輸入流之前清除輸入流中的額外字符。 執行此操作的標准方法是:

int c;

while ((c = getchar()) != '\n' && c != EOF)
    continue;

這會丟棄輸入流中的字符,直到到達換行符或EOF 請注意, getchar()在發生錯誤時返回EOF ,並且用戶也可能輸入EOF ,因此有必要對其進行顯式測試以避免可能的無限循環。

暫無
暫無

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

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