Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you scan for a single character in C?

Tags:

c

parsing

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!

like image 634
joshiapoorav Avatar asked Jul 16 '20 04:07

joshiapoorav


People also ask

How do I scan a single character?

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 .

What is the function to read a single character in c?

Read a single character. For example, char ch; scanf("%c", &ch); reads one character and stores that character into ch.

Can we use scanf for character?

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.


2 Answers

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();
like image 114
chux - Reinstate Monica Avatar answered Oct 18 '22 02:10

chux - Reinstate Monica


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
like image 27
Rohan Bari Avatar answered Oct 18 '22 04:10

Rohan Bari