繁体   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