簡體   English   中英

從C中的輸入文件讀取特定短語

[英]Reading specific phrases from input file in C

晚上的最后一個問題。 我盡量避免在每次斗爭中張貼多於一次的內容哈哈...

這有點簡單。

我有一個txt文件,在前8行中包含一系列排列的數字。 之后的每一行都是一個特定的詞組,例如“ BUY ITEM”或“ AWARD ITEM”,后跟一個整數(有幾個詞組,但我只關心一個)。 基本上,我試圖建立一個for或while循環,以便在其中可以檢測文檔中的短語,將指針設置為短語的末尾,然后將fscanf設置為短語右邊的整數。 我遇到的唯一麻煩是將指針指向特定短語的結尾,然后讀取數字。 以及該短語在不同的行上重復的事實,我不希望一次取所有值。

我敢肯定我可以做一個簡單的

while (!feof(//function for reading phrase)) {
      fscanf("%d", &value);
      //rest of function

那就是那樣。 但是我已經嘗試了fseek和fget,但是沒有預先設置要去的位置的方法,實際上沒有什么能幫助您將指針指向我需要的位置。 每次輸入文件都會不同,所以我不能僅僅告訴它向下移動1024個空格或類似的內容。 只是不確定您會怎么做...

下面也是輸入文件的示例。

75 75 908
10 10
18 23.10 10.09
70 5 15
8 100 20 28.99
30 40 50 60
4 6 8 8 5 5 5 6 7 10
10
BUY ITEM 8
BUY ITEM 10
AWARD ITEM 7
BUY ITEM 1
BUY ITEM 3
AWARD ITEM 9
BUY ITEM 7
RETURN ITEM 8

非常感謝任何人的幫助。

這是一種簡單的方法,使用以下事實:如果文件中的文件采用相同格式,則數字將始終以該行的相同字符出現。 這有點脆弱,例如,最好使您的程序更健壯,以應付任意數量的空格,但我將其作為練習留給您:

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

#define MAX_LEN 100
#define BUY_LEN 9
#define AWARD_LEN 11

int main(void) {
    FILE * infile = fopen("file.dat", "r");
    if ( !infile ) {
        perror("couldn't open file");
        return EXIT_FAILURE;
    }

    char buffer[MAX_LEN];
    char * endptr;

    while ( fgets(buffer, MAX_LEN, infile) ) {
        if ( !strncmp(buffer, "BUY ITEM ", BUY_LEN ) ) {
            char * num_start = buffer + BUY_LEN;
            long item = strtol(num_start, &endptr, 0);

            if ( endptr == num_start ) {
                fprintf(stderr, "Badly formed input line: %s\n", buffer);
                return EXIT_FAILURE;
            }

            printf("Bought item %ld\n", item);
        }
        else if ( !strncmp(buffer, "AWARD ITEM ", AWARD_LEN) ) {
            char * num_start = buffer + AWARD_LEN;
            long item = strtol(num_start, &endptr, 0);

            if ( endptr == num_start ) {
                fprintf(stderr, "Badly formed input line: %s\n", buffer);
                return EXIT_FAILURE;
            }

            printf("Awarded item %ld\n", item);
        }
    }

    fclose(infile);
    return 0;
}

使用問題中的樣本數據文件運行此命令,您將獲得:

paul@local:~/src/sandbox$ ./extr
Bought item 8
Bought item 10
Awarded item 7
Bought item 1
Bought item 3
Awarded item 9
Bought item 7
paul@local:~/src/sandbox$ 

順便說一句,基於問題中的一項建議,您可能想檢查問題while( !feof( file ) )的答案總是錯誤的

暫無
暫無

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

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