'Reading multiple lines in C using fscanf
i'm currently doing an uni project which has to read a multiple lines sequence of inputs given in a .txt format. This is my first experience with C, so i don't know much about reading files with fscanf and then processing them. The code i wrote goes like this:
#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;
}
My "init" file is formatted like this:
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
I don't know how to tell the program to skip a line after the first one is read.
Thanks for the help in advance!
Solution 1:[1]
There's no reason to use a char array (string) when you're only going to read one character.
Do this:
char tipo;
and
fscanf(stream, " %c %f %f %f %f%", &tipo, &n1, &n2, &n3, &n4);
and your code should work. Note the c instead of s.
Solution 2:[2]
In response to "I don't know how to tell the program to skip a line after the first one is read."Just do this!
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);
}
Also there is no point in using an 1-element array. If you wish to just use a char element change it from char tipo [1]; to char tipo; and your respective "%s" to "%c". But if you wish it to be a string element : change it from char tipo [1]; to char *tipo; or char tipo [n]; and keep your "%s".
Solution 3:[3]
Use fscanf(stream, "%*[^\n]\n") to skip line. Just add one if statement to check line number to skip. if (i == 2) to skip second line.
Also change char tipo[1] to char tipo and change "%s" to "%c" in printf and 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);
}
Also you are opening file twice. if(streem = fopen("init.txt", "r") == NULL) will be true because you have already opened file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Aditi Rawat |
| Solution 3 |
