簡體   English   中英

使用fscanf在C中讀取多行

[英]Reading multiple lines in C using fscanf

我目前正在做一個uni項目,該項目必須讀取以.txt格式給出的多行輸入序列。 這是我第一次使用C,因此我對使用fscanf讀取文件然后進行處理並不了解。 我寫的代碼是這樣的:

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

int main() {
    char tipo [1];
    float n1, n2, n3, n4;
    int i;
    FILE *stream;
    stream=fopen("init.txt", "r");
    if ((stream=fopen("init.txt", "r"))==NULL) {
        printf("Error");
    } else {
        i=0;
        while (i<4) {
            i++;
//i know i could use a for instead of a while
            fscanf(stream, "%s %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);
            printf("%s %f %f %f %f", tipo, n1, n2, n3, n4);
        }
    }
    return 0;
}

我的“ init”文件的格式如下:

L 150.50 165.18 182.16 200.50
G 768.12 876.27 976.56 958.12
A 1250.15 1252.55 1260.60 1265.15
L 200.50 245.30 260.10 275.00
A 1450.15 1523.54 1245.17 1278.23
G 958.12 1000.65 1040.78 1068.12

我不知道如何在讀取第一個后告訴程序跳過一行。

我在這里先向您的幫助表示感謝!

使用fscanf(stream, "%*[^\\n]\\n")跳過行。 只需添加一個if語句來檢查要跳過的行號。 if (i == 2)跳過第二行。 還要將char tipo[1]更改為char tipo並在printffscanf中將“%s”更改為“%c”

while (i++ < 4) 
{
    if (i == 2) // checks line number. Skip 2-nd line
    {
        fscanf(stream, "%*[^\n]\n");
    }
    fscanf(stream, "%c %f %f %f %f\n", &tipo, &n1, &n2, &n3, &n4);
    printf("%c %f %f %f %f\n", tipo, n1, n2, n3, n4);
}

另外,您要打開文件兩次。 if(streem = fopen("init.txt", "r") == NULL)將為true,因為您已經打開了文件。

響應“ 我不知道如何在讀取第一個代碼后告訴程序跳過一行 。”請執行此操作!

while (i<4) 
{
    i++;
    //i know i could use a for instead of a while
    fscanf(stream, "%s %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);
    if(i != 2) //skipping second line
        printf("%s %f %f %f %f", tipo, n1, n2, n3, n4);

}

同樣,使用1元素數組毫無意義。 如果您只想使用char元素,請從char tipo [1];更改它char tipo [1]; char tipo; 以及您各自的"%s""%c" 但是,如果您希望它是一個string元素,請從char tipo [1];更改char tipo [1]; char *tipo; char tipo [n]; 並保留您的"%s"

當您只打算讀取一個字符時,沒有理由使用char數組(字符串)。

做這個:

char tipo;

fscanf(stream, "%c %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);

並且您的代碼應該可以工作。 注意c而不是s。

暫無
暫無

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

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