One Line at a Time, With Recovery

Medium

The lesson's line loop, written out for real. main is yours to finish and the template already carries its shape: char line[64] is the buffer, lines_read counts how many lines arrived, and while (fgets(line, sizeof(line), stdin) != NULL) reads until the input runs out, since fgets returns NULL when it stored nothing at all. Two pieces are missing from the body and the lesson spelled both of them out. The first is the strip. fgets keeps the newline whenever the whole line fitted in the buffer, so line holds the text that was typed followed by '\n', and the template never removes it. Write size_t length = strlen(line); and then if (length > 0 && line[length - 1] == '\n') { line[length - 1] = '\0'; }, which measures the string, checks that the last character really is a newline before touching it, and moves the end of the string back by one byte. The guard is not decoration here, because the last line of an input often arrives with no newline at all and an unconditional chop would eat a real character, turning a good line into a bad one. The second missing piece is the check on the parse. sscanf(line, "%d %d", &left, &right) returns the number of conversions it completed, exactly as scanf has since chapter 2, and the template throws that number away and prints a sum regardless, which is why a line of words reports 0 + 0 = 0. Branch on the count instead. When it is 2, print the sum in the form 7 + 3 = 10, with single spaces around the plus and the equals sign. When it is anything else, print bad line: followed by a space and the line itself, and print the stripped line rather than the raw one, since the newline you removed is the difference between one line of output and one line plus a blank one. Two ordinary cases are worth getting right. A line holding a single number converts one value and returns 1, which is not 2, so it is a bad line even though there was a number on it. And an input with no lines at all never enters the loop, which is what lines_read is for: print no input once, after the loop, when the count is still 0. Do not reach for scanf("%s", ...) anywhere in this program, and do not enlarge the buffer to dodge the newline. main returns 0 on its only path, since the checker treats a nonzero exit status as a failure however correct the printed output looks.

Success Criteria

Your code must pass 4 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.

This platform is built by its community

Every lesson, project, and tool on HelloC++ is funded by sponsors. Join them and help shape what we build next.

Become a Patron