簡體   English   中英

如何在C的同一行中掃描字符串(帶空格)和整數

[英]How to scan a string(with space) and an integer in the same line in C

我輸入的是“ SAME AS 1”。 在此,“ SAME AS”是字符串,“ 1”是整數。 如果它們在同一行中,我如何將它們都作為輸入。

使用[^ \\ n]並沒有幫助,因為它還會將“ 1”作為字符串的一部分。 使用[^ 0-9]也無濟於事,因為相同的scanf命令將必須輸入不以數字結尾的“ LEFT”或“ RIGHT”。

有沒有一種方法可以組合[^ \\ n]和[^ 0-9]? 還有其他方法嗎?

PS:無法更改輸入。

scanf()不在乎換行符

到目前為止,您可以這樣做:

#include <stdio.h>

int main(void)
{
    char buffer[64];

    int rc;
    int number;
    while ((rc = scanf("%63[^\n0-9]%d", buffer, &number)) != EOF)
    {
        if (rc == 0)
        {
            printf("Nothing read!\n");
            int c;
            while ((c = getchar()) != EOF && c != '\n')
                ;
        }
        else if (rc == 1)
            printf("Simple word - no number [[%s]]\n", buffer);
        else
            printf("Word and number [[%s]] %d\n", buffer, number);
    }
    return 0;
}

這將捕獲並測試scanf()的結果。 例如,給定數據文件:

SAME AS 1
LEFT
RIGHT

該程序的內容如下:

Word and number [[SAME AS ]] 1
Nothing read!
Simple word - no number [[LEFT]]
Simple word - no number [[RIGHT]]

也可以在“單詞和數字”報告之后添加“字符吞噬”循環。 最好創建一個微功能來做到這一點:

static inline void gobble(void)
{
    int c;
    while ((c = getchar()) != EOF && c != '\n')
        ;
}

首先在數據文件中添加一個帶有數字的行,如下所示:

SAME AS 1
LEFT
RIGHT
123 ANGELS

你會得到:

Word and number [[SAME AS ]] 1
Nothing read!
Simple word - no number [[LEFT]]
Word and number [[RIGHT]] 123
Simple word - no number [[ ANGELS]]

scanf()系列函數幾乎不關注換行符或其他空格,除非您強迫它們這樣做。 整個文件也可以在一行上,也可以在每行上包含每組非空白,並產生幾乎相同的輸出。

您確實關心換行

如果要基於行的輸入,最好先讀取行,然后解析結果。 這還有一個好處,您可以更連貫地報告錯誤。 例如:

#include <stdio.h>

int main(void)
{
    char line[4096];

    while (fgets(line, sizeof(line), stdin) != NULL)
    {
        char buffer[64];
        int number;
        int rc = sscanf(line, "%63[^\n0-9]%d", buffer, &number);
        if (rc == 0)
            printf("Nothing read! (line = [[%s]])\n", line);
        else if (rc == 1)
            printf("Simple word - no number [[%s]]\n", buffer);
        else if (rc == 2)
            printf("Word and number [[%s]] %d\n", buffer, number);
        else
            printf("sscanf() returned %d - can't happen (but did)?\n", rc);
    }
    return 0;
}

並在第一個文件上運行:

Word and number [[SAME AS ]] 1
Simple word - no number [[LEFT]]
Simple word - no number [[RIGHT]]

第二個文件:

Word and number [[SAME AS ]] 1
Simple word - no number [[LEFT]]
Simple word - no number [[RIGHT]]
Nothing read! (line = [[123 ANGELS
]])

很難使用任何scanf()函數族並避免在SAME AS數據上尾隨空格-除非您利用“兩個單詞加數字”或“一個單詞加數字”或“一個單詞”,這將需要“讀取行”示例(第二個程序),並使用sscanf()多次嘗試。

scanf()系列函數非常非常非常難以准確使用。 通常,讀取一行並使用sscanf()有助於降低復雜性,但是即使那樣也並不完美。 有關該主題的更多想法,請參見遠離scanf()新手指南

暫無
暫無

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

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