Reputation: 63
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.
Thank you!
Upvotes: 5
Views: 177
Reputation: 154070
Use *
to scan but not save
fscanf(fp, "%d %*f %c %c", &studentID, &i1, &i2);
// ^^^ Scan but do not save the GPA
Wise to check return value for success.
*
specifiers do not count toward the result.
if (fscanf(fp, "%d %*f %c %c", &studentID, &i1, &i2) == 3) Success();
Upvotes: 6
Reputation: 7726
Use %*f
wherever you need to skip the word (since the GPA was a floating point) to be read. For example:
fscanf(fp, "%d %*f %c %c", &studentID, &i1, &i2);
12345 3.5000 a j
^^^^^________^_^ // ^ will be read
Upvotes: 6