int main(void)
{
int i, a[10], sum = 0;
int * b;
b = a;
char c[10];
printf ("Please enter some numbers:\n");
for(i = 0 ; i < 10 ; i++)
{
(void) fgets(c, (sizeof * b), stdin);
if(c[0] == '\n')
{
break;
}
*(b + i) = atoi(c);
sum = sum + *(b + i);
}
printf ("sum : %d \n", sum);
return 0;
}
$Please enter some numbers:
$32
$31
$1
$
$sum:64
$Please enter some numbers:
$123
$sum:123
$Please enter some numbers:
$12
$123
$sum:135
$Please enter some numbers:
$2123
$
$sum:215 //The sum became 212+3.
$Please enter some numbers:
$12345
$11
$
$sum:179 //The sum became 123+45+11.
$Please enter some numbers:
$123456
$sum:579 //If the number of digits is a multiple of 3, this program directly prints sum(=123+456).
This is wrong:
fgets(c,sizeof* b,stdin);
sizeof *b is the size of an int (tipically 4) and you want room for 10 characters:
fgets(c,sizeof c,stdin);
And notice that you don't need to strip the trailing new-line after fgets in this concrete case, from the atoi man:
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With