簡體   English   中英

如何使用scanf掃描多個單詞?

[英]How to use scanf to scan for multiple words?

我正在嘗試處理接受輸入、最小字符限制和最大字符限制的 function。 即使有 2 個或更多單詞,我也需要接受輸入並計算字母,我看到人們說scanf("%30[^\n]%*c")可以解決問題。 但是,這僅在它是第一個輸入時才有效,僅此而已。 如果上面有任何輸入,它將終止該行,將 count 保留為零,並無限運行循環。 有誰知道為什么?

注意:我不能使用 <string.h> header 文件中的任何內容。

{
    int n = 1;
    
    while (n == 1)
    {
        int count = 0;
        scanf("%30[^\n]%*c", input);
        while (input[count] != '\0')
        {
            count++;
        }
        if (minimum == maximum)
        {
            if (count > maximum)
            {
                printf("String length must be exactly %d chars: ", minimum);
            }
            else if (count == minimum)
            {
                n = 0;
                return input;
            }
            else if (count < minimum)
            {
                printf("String length must be exactly %d chars: ", minimum);
            }
        }
        else 
        {
            if (count > maximum)
            {
                printf("String length must be no more than %d chars: ", maximum);
            }
            else if (minimum <= count && count <= maximum)
            {
                n = 0;
                return input;
            }
            else if (count < minimum)
            {
                printf("String length must be between %d and %d chars: ", minimum, maximum);
            }
        }
    }
}

scanf("%30[^\n]%*c", input);的問題如果來自stdin的新字節是換行符,它是否會失敗,返回0並保持input不變,可能未初始化,導致代碼的 rest 具有未定義的行為。

另請注意,此格式將導致scanf()在轉換后讀取並丟棄待處理的字節,無論是換行符,這是您的意圖,還是用戶在輸入行上鍵入的任何第 31 個字符。

您應該測試scanf()的返回值以檢測轉換錯誤和/或文件結尾,並且僅在scanf()返回1時掃描數組。

您應該在行尾使用循環丟棄多余的字節:

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

或使用scanf()

scanf("%*[^\n]");  // discard the rest of the input line if any
scanf("%*c");      // discard the newline if any.

要擺脫先前調用scanf()留下的掛起換行符,您可以編寫:

int c;
if ((c = getchar()) != '\n')
    ungetc(c, stdin);

或使用scanf

scanf("%1*[\n]");  // read and discard at most 1 newline byte

暫無
暫無

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

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