Input with input.h
So far every value is written in the code. Let the user type the year of birth and three grades instead.
input.h
Your repository already has a helper library, input.h. It has three functions:
int read_int(const char *prompt); /* a whole number */
double read_double(const char *prompt); /* a real number */
void read_line(const char *prompt, char text[], int size); /* a line, topic 9 */
read_int("Year of birth: ") prints the question, waits until you type a number and press Enter, and returns it. If what you type isn't a number, it asks again:
Year of birth: 2007
Grade 1: nine
Not valid: enter a whole number.
Grade 1: 9
C also has a standard function, scanf, but it is treacherous with wrong input: the unread text stays waiting and spoils the next read. read_int doesn't let that happen. You'll see how it works inside in topic 9.
Connect the library
Two changes.
CMakeLists.txt: the program will use the library course_input:
target_link_libraries(p02_card PRIVATE course_input)
main.c: #include "input.h" at the top. Quotes, not < >, because it is our own file, not the standard library. Then, in place of the written-in values:
int birth_year = read_int("Year of birth: ");
int g1 = read_int("Grade 1: ");
int g2 = read_int("Grade 2: ");
int g3 = read_int("Grade 3: ");
double average = (g1 + g2 + g3) / 3.0;
Why 3.0 and not 3
Try it with / 3 first and type 9, 8, 8:
Average: 8.00
It should be 8.33. g1 + g2 + g3 is an int, 3 is an int too, and dividing two whole numbers throws the fraction away: 25 / 3 = 8. Only then is 8 stored in the double and becomes 8.00. It is enough for one side of the division to be a double: 3.0.
Arithmetic and changing the type
| Operation | int and int |
If at least one is a double |
|---|---|---|
+ - * |
7 * 2 → 14 |
7 * 2.0 → 14.0 |
/ |
185 / 60 → 3 |
7 / 2.0 → 3.5 |
% |
185 % 60 → 5 (the remainder) |
not allowed |
Together, / and % turn minutes into hours and minutes: 185 min = 3 h 5 min.
You can also change the type by hand, by writing the wanted type in parentheses before the value (a cast):
(double)sum / 3:sumis turned into adoublebefore the division, so the division is a real one.(int)8.75→8: the fraction is cut off, not rounded. You round like this:(int)(x + 0.5). This works only for non-negative numbers:(int)(-2.7 + 0.5)gives-2, though it should be-3.
With / 3.0, run it again and type 2007, 9, 8, 8:
Year of birth: 2007
Grade 1: 9
Grade 2: 8
Grade 3: 8
Year of study: 1
Group: PI25A
Age: 19 years
Average: 8.33
In memory: int 4 B, double 8 B, char 1 B
Commit: Read input with input.h.