Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string atoi int array

Tags:

arrays

c

I want to do the following stuff:

  1. Convert input string to int.
  2. Sum up an int array by using pointers and a for loop.
  3. If the user types nothing but only ENTER, the program will print the answer.

My code:

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;
}

There is something weird that I can't figure out why.

It only works fine with two-digits:

$Please enter some numbers:
$32
$31
$1
$
$sum:64

If I type three-digits, it directly prints result:

$Please enter some numbers:
$123
$sum:123


$Please enter some numbers:
$12
$123
$sum:135

If there are more than three digits, the program will sum up rest of the digits.

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

If someone can help me, I would be grateful. Thank you for reading this long question.

like image 570
Xenoturbellian Avatar asked Jul 18 '26 04:07

Xenoturbellian


1 Answers

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.

like image 195
David Ranieri Avatar answered Jul 20 '26 23:07

David Ranieri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!