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!
So, to read a single character from console, give the format and argument to scanf() function as shown in the following code snippet. char ch; scanf("%c", ch); Here, %c is the format to read a single character and this character is stored in variable ch .
Read a single character. For example, char ch; scanf("%c", &ch); reads one character and stores that character into ch.
The scanf() function reads format-string from left to right. Characters outside of format specifications are expected to match the sequence of characters in stdin ; the matched characters in stdin are scanned but not stored. If a character in stdin conflicts with format-string, scanf() ends.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With