我目前正在做一个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
我不知道如何告诉程序在读完第一行后跳过一行。
谢谢你提前提供帮助!
发布于 2017-10-26 10:29:11
当您只读取一个字符时,没有理由使用char数组(string)。
这样做:
char tipo;
和
fscanf(stream, " %c %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);
你的代码应该能用。注意c
而不是s。
发布于 2017-10-26 10:40:50
使用fscanf(stream, "%*[^\n]\n")
跳过行。只需添加一条if
语句,以检查行号以跳过。if (i == 2)
跳过第二行。还将char tipo[1]
更改为char tipo
,并在printf
和fscanf
中将"%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)
将为真,因为您已经打开了文件。
发布于 2017-10-26 10:48:11
在回答“我不知道如何告诉程序跳过一行后,第一读。”只要这样做!
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"
。
https://stackoverflow.com/questions/46951872
复制相似问题