Create a program that calculates the sum of the numbers in each input line.
Each input line ends with a newline character. The numbers are between 0 and 100, and they are separated by a single space. The length of the lines are not specified, but we can suppose that the sum can be stored in a variable of type int.
For each line of the input, the program must print one line containing the sum of the numbers. Each line must be terminated by a newline character.
Output for Sample Input
Hints and Guide
We recommend processing the input character by character. Three kinds of symbols can appear: a decimal digit as a part of a number, a space that indicates the starting point of a new integer, and a newline character.
We can use an integer variable to store the number constructed from its decimal digits. Any time a new digit appears, the stored number must be multiplied by 10 and then incremented by the integer value of the digit. To calculate the integer value of the digit, it is enough to subtract the ASCII code of zero from the ASCII code of the digit.
Another integer is required to store the subtotal of the current line. Any time a character other than a digit is read from the standard input, we have to increase the subtotal by the amount stored in the variable defined just above. Do not forget to reset that variable to 0 because later we will use it to construct another integer.
When the input character is a newline, then the current value of the variable containing subtotal can be considered as the sum of the line. Do not forget to reset this variable to 0 because later we will use it to store the sum of another line.
One possible solution is available in: main.c.
Acknowledgement This work was supported by the construction EFOP-3.4.3-16-2016-00021. The project was supported by the European Union, co-financed by the European Social Fund.
|University of Debrecen; Faculty of Informatics; v. 03/01/2019|