My friend and I are working on a project, and we need to read input from a file in C.
The file looks like this:
15 25 200
3 10
17.99 22.99 109.99
100 2 4
5.99 99.99 20.00 49.99
10 10 10 10 10 10 10 10 10 10
3.99 5.99 7.99 8.00 5.00 5.00 5.00 6.00 7.00 9.99
5
I need to read the file line by line, and set each value equal to a different variable. For example, the first value on the first line must be set to the variable preSalePrices, the second value doorPrices, and the third preSales. I need help figuring out how to specify the number of values on each line. For example, how do I tell the program to get three values on the first line, but only two on the second line? Then four values on the fifth line, and so on.
Here is my code, but it just crashes:
int main() {
float preSalePrices, doorPrices;
int preSales;
FILE *fp;
fp = ("C://Users//Jake//Desktop//Charity Ball//auction01.txt", "r");
while(fscanf(fp, "%f %f %i", &preSalePrices, &doorPrices, &preSales) != EOF) {
printf("%f, %f, %i", preSalePrices, doorPrices, preSales);
}
}
I've looked all over the internet and I can't find anything related to this specifically.
If you always know the number of values in each line, you can just ignore the end-of-lines and read the values one by one.
If the end-of-lines are important the easiest way is to read each line separately (e.g.
fgets
) and then read the data from there, withsscanf
.