I have one char variable that holds number which represents examID(it’s char because it has to be char). My text file looks like this:
5 1 Exam 1 (audit 31.10.)
6 1 Exam 2 (audit 23.10.)
14 1 Lab 01 (audit 21.11.)
16 1 Lab 02 (audit 28.11.)
...
First number in each line is examID, second is max num of points for that exam, end rest of text in line is exam name. I need to search text for examID match, and if it is match i need to store max num of points, and exam name in variables for later use. This is what i have so far:
char examName[100];
char tmp[100];
int examID;
int maxPoint=0;
FILE *fin=fopen("Exams.txt", "r");
while(fgets(tmp, sizeof(char)*100, fin)!=NULL) {
sscanf(tmp, "%d", &examID);
if(examID==s.examNum)
printf("%d", examID);
}
So i found match and printed it, and it’s ok, but i don’t know how to read second number in line and name of exam.
You were almost there:
fgetsreads the full like, thensscanfparses it as the format string shows. So if you need a number, then number, then string (as in this case) you can use"%d %d %[^\n]"Note: Since the
examNamehas spaces (and is the list part of the text file before the newline) we use the negated scanset tellingsscanf“I want everything until a newline is found stored as a string”Side note, initialize your vairables: