簡體   English   中英

C:從用戶讀取整數對,直到換行符(scanf,sscanf,fgets和朋友)

[英]C: Reading pairs of ints from user until newline (scanf, sscanf, fgets and friends)

我正在嘗試從stdin讀取未知對,直到輸入新行。

輸入示例:

輸入內容:

5

輸入對:

1 3 4 2 5 2 5 4

最好的方法是什么? 我嘗試了幾種方法,包括fgets和sscanf-但無法獲得預期的結果。

這是我嘗試過的方法,但我一直想不到\\ n:

方法1:

while (1)
{
    scanf("%d %d", &a, &b);

    // do something with a,b

    if (getchar() == '\n')
        break;
}

方法2:

while (scanf("%d %d", &a, &b) == 2)
{
    // do something with a,b

    if (getchar() == '\n')
        break;
}

我一直陷入無限循環-我在做什么錯?

我認為處理行尾空格的最簡單方法(這可能是導致您出現問題的原因)是提前閱讀行並用sscanf解析。 它可能看起來像這樣:

#include <stdio.h>

int main() {
  char line[1024];
  char const *p;
  int x, y;
  int n;

  fgets(line, 1024, stdin);

  for(p = line; sscanf(p, " %d %d%n", &x, &y, &n) == 2; p += n) {
    printf("%d %d %d\n", x, y, n); // to show you what happens
  }

  return 0;
}

在這里, %n使sscanf告訴您到該點為止已處理的字符數,並且在每次迭代中,我們使用該數字來提高讀取指針。

這通過忽略最后一個來處理一行中數量不均勻的數字,這可能是也可能不是您想要發生的情況。

您會遇到無限循環,因為最后一位讀取后的下一個字符不是換行符而是空格

因此,如果您輸入此輸入

1 3 4 2 5 2 5 4 

這是

1<space>3<space>4<space>2<space>5<space>2<space>5<space>4<Enter>

您可以使其正常工作(請注意輸入中最后一個數字4后面的最后一個字符)

讓我們來分析上面的例子

1<space>3<space>
|       |  |-----> will be stored in getchar()
|       |--------> will be stored in b 
|----------------> will be stored in a 

因此對於最后兩位數字,如果您打了空格而不是Enter鍵,這將發生

5<space>4<space>
|       |  |-----> will be stored in getchar() which is not newline 
|       |          so it will generate another loop 
|       |--------> will be stored in b 
|----------------> will be stored in a 

因此程序將等待輸入數字,因為創建了另一個循環並將其停留在該循環中,因為沒有剩余數字!

要解決該問題,您可以使用fgets()函數將整行存儲在字符串中,然后使用sscanf()函數從中獲取一對數字

暫無
暫無

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

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