簡體   English   中英

使用fscanf讀取空格

[英]Read whitespaces with fscanf

我想從存儲如下數據的文件中讀取:

Max Mustermann 12345

現在,我想使用以下代碼讀取數據:

FILE *datei;
char text[100];
int il;

datei = fopen ("datei.txt", "r");

if (datei != NULL)
{
    fscanf(datei, ": %s %d", text, &il);

    printf("%s %d", text, il);
    fclose(datei);
}

但是此代碼僅掃描“ Max”(因為存在空格),然后掃描下一個“ int”的“ Mustermann”。 我要排序'Max Mustermann'是char數組,而int則是'12345'。 如何使用fscanf讀取空白? 還是有其他方法可以從文件中獲取不同變量中的值?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    FILE *datei;
    char text[100];
    char line[128], *p;
    int il;

    datei = fopen ("data.txt", "r");

    if (datei != NULL){
        if (fgets(line, sizeof(line), datei) != 0){ //read one line
            p=strrchr(line, ' ');//search last space
            *p = '\0';//split at last space
            strcpy(text, line);
            il = atoi(p+1);//or sscanf(p+1, "%d", &il);
            printf("%s, %d", text, il);
        }
        fclose(datei);
    }
    return 0;
}

也使用fscanf。

char *p;
//"%[^0123456789] is reading other digit character
fscanf(datei, "%[^0123456789]%d", text, &il);
p=strrchr(text, ' ');//search last space
*p = '\0';//replace last space (meant drop)
printf("%s, %d", text, il);

手工制作的?

#include <ctype.h>
    if (datei != NULL){
        int ch, i=0;
        while(EOF!=(ch=fgetc(datei)) && i<100-1){
            if(isdigit(ch)){
                ungetc(ch, datei);
                text[--i] = '\0';
                break;
            }
            text[i++] = ch;
        }
        if(i >= 99){
            fprintf(stderr, "It does not conform to the format\n");//maybe no
            fclose(datei);
            return -1;
        }
        fscanf(datei, "%d", &il);
        printf("%s, %d\n", text, il);
        fclose(datei);
    }

這取決於文件的格式。 如果它始終是first-name space last-name space number那么您可以使用兩個%s來獲取名字和姓氏。

if (fscanf(datei, "%s %s %d", text1, text2, &il) == 3)
    ...then OK...
else
    ...failed...

例如,如果該數字前面帶有特殊/唯一字符(例如“!”),則可以使用類似scanf的格式?

if (fscanf(datei, "%[^!]!%d", text, &il) != 2)
    ...

除非您可以保證數字前總是有兩個名稱,或者可以刪除文件名(可能是名稱和數字之間的逗號),否則實際上沒有任何方法可以自動執行您想要的操作。

如果名字叫什么:Max Mustermann 3rd

我認為數據輸入文件需要先進行“清理”,然后才能進行處理。

暫無
暫無

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

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