使用fscanf读取C中的多行

使用fscanf读取C中的多行,c,scanf,C,Scanf,我目前正在做一个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.

我目前正在做一个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;
}
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
我不知道如何告诉程序在第一行被读取后跳过一行


提前谢谢你的帮助

当您只读取一个字符时,没有理由使用字符数组(字符串)

这样做:

char tipo;

你认为代码应该有效。注意c而不是s。

使用
fscanf(流,“%*[^\n]\n”)
跳过行。只需添加一个
if
语句来检查要跳过的行号
if(i==2)
跳过第二行。 同时将
char tipo[1]
更改为
char tipo
,并在
printf
fscanf

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);
}
while(i++<4)
{
if(i==2)//检查行号。跳过第二行
{
fscanf(流,“%*[^\n]\n”);
}
fscanf(流,“%c%f%f%f\n”、&tipo、&n1、&n2、&n3、&n4);
printf(“%c%f%f%f%f\n”,tipo、n1、n2、n3、n4);
}
您还将打开文件两次<代码>如果(streem=fopen(“init.txt”,“r”)==NULL)将为真,因为您已经打开了文件。

响应“我不知道如何告诉程序在读取第一行后跳过一行。”只需这样做

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);

}

while(i将
&tipo
的值作为第一个参数在两个方面是不正确的:您正在传递一个指向一个字符数组的指针,但是
%s
需要一个指向缓冲区第一个字符的指针,该字符具有足够的空间来读取非空白字符字符串。C中的字符串以null结尾,因此在您的情况下,会写入两个字符,但t您的数组中有1的空间。我假设您的代码不起作用。请解释如何操作。通常,避免使用
scanf
fscanf
。它们非常难使用。使用
fgets
一次读取每一行,然后您可以对每个结果字符串使用
sscanf
。如果我错了,请纠正我。这是您想要的输出吗?L 150.50 165.18 182.16 200.50 A 1250.15 1252.55 1260.60 1265.15 A 1450.15 1523.54 1245.17 1278.23我认为,
fscanf
是出了名的难以使用。它非常容易。非常感谢您的帮助,尤其是对fopen==null的帮助。因为我是新手,我不知道只要删除stream=fopen(“init.txt”,“r”)因为你要打开文件两次。你不需要它。是的,我不需要字符串,所以这对我有帮助!
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);

}