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 int
s 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
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
.
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.
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