Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using atoi to fill an array of ints

Tags:

arrays

c

atoi

First time asking a question on here. Apologies if there's already threads about this but i had a few searches and didn't quite find what i think i was looking for. I'm very new to C and am working through a few homework exercises for my microcontroller systems class. We're currently working through easy exercises before we get into embedded C and I'm trying to write a program that'll take a line of text consisting of 10 numbers separated by commas and fill an array of ints with it. As a hint we were told to use a substring and atoi. I think i'm close to getting it right but i can't get it to output my numbers properly.

Also i'm not looking spoon fed answers. A few hints would suffice for now. I'd like to try figuring it out myself before asking for the solution.

Here is my code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int a[10];
    char str[] = {1,2,3,4,5,6,7,8,9,10}; //contains string of numbers
    int i;
    puts("This prints out ten numbers:");

    for (i = 0; i < 10; i++)
    {
        a[i] = atoi(str);
        printf("%d", a[i]);
            //i'm guessing the problem lies in one of the above two lines
    }
    return 0;
}

This is outputting the following:

This prints out ten numbers:
0000000000

Thanks to anyone that can help! Chris

like image 939
Chris Lyttle Avatar asked Oct 05 '22 19:10

Chris Lyttle


2 Answers

You said that you have to use a line of text separated by commas but you've actually declared a char array containing ten (binary) integers. To get that into a string you just need to do this:

char str[] = "1,2,3,4,5,6,7,8,9,10";

Then you'll need someway to process this string to get each number out and into your array of int.

like image 100
teppic Avatar answered Oct 10 '22 11:10

teppic


First off, you should declare a string as follows:

char str[] = {"1,2,3,4,5,6,7,8,9,10"};

the " made the numbers a whole string. Next, you'll need to tokenize them and using the <string.h> library which will come quite handy in this situation.

Here is how you do tokenizing:

define a token buffer first:

char* token;

token = strtok(str,",");   //think of it as substring, the part of the str before the comma
for (i = 0; i < 10; i++)
{
    a[i] = atoi(token);
    printf("%d\t", a[i]);
            //i'm guessing the problem lies in one of the above two lines
    token = strtok(NULL, ","); //this line is also required for tokenizing the next element
}

Using the strtok() function, you separated the elements between the comas, and got yourself the number strings. Used atoi() function to convert them into integers and printed them. You can see this reference for strtok() function for better understanding.

like image 45
Varaquilex Avatar answered Oct 10 '22 12:10

Varaquilex