I have been a longtime viewer of Stack Overflow, but this is my first question. As such, please forgive and correct me if I am missing any important details or information!
I am just beginning to program in C. I'm trying to create a program that will take in a text file I specify via my console on run time and using stdin. This text will will be formatted in the following way:
10 2 2012
3 765 821 764
5 856 976 847 757 789
4 838 842 832 815
4 809 815 789 765
The first 3 numbers are the month, day, and year. After that the following lines contain data. The first number on each line represents the amount of data readings following it. I need to perform calculations based on the numbers following the first number after each line. So far I have been using the scanf function to obtain the data for the date and print it out as a heading.
#include <stdio.h>
int main()
{
// Define Variables
int month;
int day;
int year;
// Scan text file for month, day and year
scanf("%d", &month);
scanf("%d", &day);
scanf("%d", &year);
// Print out date and headers
printf("\nTest date: %d/%d/%d", month, day, year);
printf("\nLED Lumens\n");
return 0;
}
I need to be able to take the numbers following the first number in each line. I will then use these numbers to calculate various things (which I don't need help with). My question is what's the best way to do this? My idea would be to use scanf to get the first number in the row, then loop until the number of values in the line is reached, scanning the number each time.
So, if I scan the first number and it's a 3, I will loop and scan the next 3 numbers. I will then perform the calculations for those numbers, then repeat for each line.
Is this the right way to go about this, and will this work? Mainly I'm wondering how scanning the data from the text works. Every time I use the scanf function does it just obtain the next number in my text file. Does it work regardless that my data is on the following line?
Also note that I have not learned any of the advanced functions for dealing with text files. Hence, I am sticking to scanf to obtain the data.
Thanks! Let me know if I need any more details or clarification.
Update
Thanks to everyone who responded. I appreciate explaining how the scanf worked in the text file. I was able to get my program working. As for everyone who also responded with different functions and methods I could use, thanks! I will be sure to try those out at some point. I realize that there are probably easier and better ways to go about my task than the scanf function.
fgets()to read each line, thensscanf()to parse the buffer. Check results of both.scanf(), input fields are separated by whitespace (space,newline, andtab)... Additionally, the format string may contain multiple conversion specifications [e.g.scanf( "%d%d%d", &month, &day, &year );]... I know this isn't an 'answer', per se, but I wanted to note that the newlines shouldn't be trouble.