Q: Write a C program that reads in several lists of numbers, one list per line, computes the
total for each list and displays the total on the screen. The user first enters the number of
lines. For each list of numbers, the first number indicates how many elements are in the
list.
A sample input and output session is given below:
total for each list and displays the total on the screen. The user first enters the number of
lines. For each list of numbers, the first number indicates how many elements are in the
list.
A sample input and output session is given below:
Enter the number of lines:2
4 1 3 5 7
Output total: 16
5 2 4 6 8 1
Output total: 21
#include <stdio.h>
#include <string.h>
void
clear(void)
{
while (getchar() != '\n');
}
int
main()
{
int n, i;
printf("Enter the number of lines: ");
scanf("%d", &n);
clear(); //clear the input buffer such as ' ' and '\n'
for (i=0; i<n; i++)
{
char buff[100];
printf("Please input numbers in a single line:\n");
fgets(buff, sizeof(buff), stdin);
printf("The length of input is: %d\n", strlen(buff));
char *p;
p = &buff[0];
int a, sum = 0;
while (sscanf(p, "%d", &a) != 0)
{
sum += a;
while (*p!= ' ' && *p!= '\n') //delete digits
p++;
while (*p == ' ' || *p == '\n') //delete space and newline
p++;
if (strlen(p) < 1)
break;
}
printf("Output total: %d\n", sum);
}
}
I'm a bit sad that i cannot even finish this simple program after learning C for a long time...
Hard word is still needed...