【发布时间】:2018-04-07 16:35:55
【问题描述】:
我目前正在做一个 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
我不知道如何告诉程序在读取第一行后跳过一行。
提前感谢您的帮助!
【问题讨论】:
-
将
&tipo的值作为第一个参数传递在两个方面是不好的:你传递一个指向 1 个字符的数组的指针,但%s期望一个指向 char 的指针指向第一个字符缓冲区有足够的空间来读取非空白字符的字符串。 C 中的字符串以空值结尾,因此在您的情况下写入 2 个字符,但您的数组有 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出了名的难用。这很容易。 Don't use it.