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

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...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值