In: Computer Science
The following is for C programming language:
I want to scan for initials in a line of text. my line of text is as follows:
12345 3.5000 a j
12346 4.1000 s p
The first number represents the student ID, the second number represents the gpa, the third character represents the first initial and the fourth character represents the last initial of the student. My text file contains these values. The following is my code:
fscanf(fp, "%d %c %c", &studentID, &i1, &i2);
I only want to set the values up for studentID and initials. However, when I use the code, it shows that my student ID is right the first time, but it sets my initials as 3., then it says my student ID is 5000, and it sets the next initials as 5000. I am having a bit of trouble here. If you could help me, that would be great!
My general code displays this to the user:
==========================
||Student ID | Student Initials ||
||-----------------|------------------------||
|| 12345 | 3. ||
||-----------------|------------------------||
|| 50000 | aj ||
||----------------|------------------------||
Thank you!
fscanf is used to read files which have a structured format. So the format that we pass as input to fscanf function is the structure of one line in our file.
In our case, file has the following structure -
StudentID GPA Initial1 Initial2
Though we need only the Student ID and Initials in our display, we need to pass the entire structure while reading the file using fscanf, so that it can read correctly.
fscanf(fp, "%i %f %c %c", &studentID, &gpa, &i1, &i2)
Once we have read the entire line, we may just use those variables that are required in our display.
An example program has been shared below.
#include <stdio.h>
int main()
{
FILE *fp = fopen("students.txt", "r");
int studentID;
float gpa;
char i1, i2;
if (fp == NULL)
{
return 1;
}
printf("===================================\n");
printf("|| Student ID | Student Initials ||\n");
while (fscanf(fp, "%i %f %c %c", &studentID,
&gpa, &i1, &i2) != EOF)
{
printf("||--------------|------------------||\n");
printf("||\t%i\t| \t %c %c \t
||\n", studentID, i1, i2);
}
printf("||--------------|------------------||\n");
fclose(fp);
}
Screenshot
Output