A Reading That Knows What It Is
MediumRead a stream of sensor lines, each a letter and a number, and print every one of them in the form its kind calls for. The type is the lesson's payoff, a tagged union: struct Reading holds an enum ReadingKind called kind next to an unnamed union member called value, so count and celsius share one set of bytes and the tag is the only record of which of them was written. main is given to you and does the reading, looping on scanf(" %c %lf", &letter, &amount) == 2, zeroing a fresh struct Reading each time round, and printing "no readings" when the input was empty. What is missing is the two functions that make the pattern work, and they are the two halves of one obligation. set_reading takes a struct Reading * and fills it in: 'c' means a count, so kind becomes READING_COUNT and value.count takes (int)amount, since the number arrived as a double and a count is an int; 't' means a temperature, so kind becomes READING_CELSIUS and value.celsius takes amount unchanged; any other letter is READING_UNKNOWN, which needs no member written at all because nothing will be read back. Members are reached with the arrow throughout, because what the function holds is an address rather than a struct, and the rule to hold on to is that the tag and the member are written together, in the same branch, never one without the other. print_reading is the other half and it must trust the tag rather than guess: it takes a const struct Reading * because it only reads, switches on reading->kind, prints "%d items\n" for READING_COUNT and "%.1f C\n" for READING_CELSIUS, and prints "unknown reading" from the default. Keep that default even though every enumerator has a case. It is what catches READING_UNKNOWN here, and it is what would catch an integer that was never in the set at all, which the compiler is under no obligation to diagnose. Reading value.count when the tag says READING_CELSIUS is not a crash and not a diagnostic, it is a number that looks plausible and is not true, so the switch is the only thing standing between the union and a lie. main returns 0 on every path including the empty one, since the checker treats a nonzero exit status as a failure however right the output looks.
Success Criteria
Your code must pass 5 test case(s) to complete this exercise. 3 hint(s) are available if you need help.
Sign in to track your progress
You can work on exercises as a guest, but sign in to track your progress and save your submissions.