Reputation: 31
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).
Upvotes: 3
Views: 1110
Reputation: 41017
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.
Upvotes: 5
Reputation: 19864
fgets(c,sizeof(c),stdin);
size_t n = strlen(c);
if(n>0 && c[n-1] == '\n')
{
c[n-1] = '\0';
}
There is a newline character that comes with fgets()
you need to get rid of it.
Then convert the string to integer you don't know how many integers are there.
char *p;
p = strtok(c," ");
while(p != NULL)
{
b[i++] = atoi(p);
p = strtok(c, NULL);
}
Do the addition of the integers and make sure you have a check for i<10
before accessing the array.
If your termination condition is \n
before stripping the newline you can do the check what you are already doing.
Upvotes: 3