Xenoturbellian
Xenoturbellian

Reputation: 31

C string atoi int array

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.

Upvotes: 3

Views: 1110

Answers (2)

David Ranieri
David Ranieri

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

Gopi
Gopi

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

Related Questions