Read an ID, a grade letter and a CGPA, each on its own line.
What to build
A program that avoids the classic %c trap.
Requirements
- Read the three values from three lines.
- Print
ID I grade G CGPA C, with the CGPA to two decimals.
Input
Three lines: a whole number, a letter and a number.
Output
One line.
Constraints
The ID is from 0 to 1000000. The CGPA is from 0 to 4.
Example
Input:
2101
A
3.62
Output:
ID 2101 grade A CGPA 3.62
Why it works
After reading a number, the newline stays waiting in the input. The space before %c tells scanf to skip it, so that the letter is what gets read.
Examples
Example 1 · Input
2101 A 3.62
Expected output
ID 2101 grade A CGPA 3.62
Example 2 · Input
7 B 3
Expected output
ID 7 grade B CGPA 3.00
Hints
Hint 1
A plain %c reads the newline left by the previous scanf.
Hint 2
Write " %c", with a space, so that it skips whitespace first.
Hint 3
Read a double with %lf.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int id;
char grade;
double cgpa;
scanf("%d", &id);
scanf(" %c", &grade);
scanf("%lf", &cgpa);
printf("ID %d grade %c CGPA %.2f\n", id, grade, cgpa);
return 0;
}