您的位置:首页 > 其它

how to read a single line integer until '\n' is found

2013-01-24 10:57 351 查看
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:
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...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C