gpt4 book ai didi

c - 使用 fscanf 在 C 中读取多行

转载 作者:行者123 更新时间:2023-11-30 18:11:29 26 4
gpt4 key购买 nike

我目前正在做一个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

我不知道如何告诉程序在读取第一行后跳过一行。

感谢您提前提供的帮助!

最佳答案

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

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; 以及您各自的 "%s""%c"。但如果您希望它是一个 string 元素:将其从 char tipo [1]; 更改为 char *tipo; char Tipo [n]; 并保留您的"%s"

关于c - 使用 fscanf 在 C 中读取多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com