Reputation: 71
What I have is a string with some numbers (unknown amount but has a maximum), for example char string[] = "12 13 14 123 1234 12345";
and I wanna add each number to an array. So let's say I have an array int numbers[50];
and I want to add it to the array so it's like {12, 13, 14, 123, 1234, 12345}
.
I've tried a loop through the string that uses a variable as a state machine to detect if it is reading a number but the code ended up looking like spaghetti so I just lost the way I was thinking. I cannot use malloc()
or anything that allocates memory for this exercise.
Any ideas?
Upvotes: 0
Views: 601
Reputation: 310990
Here you are.
#include <stdio.h>
int main(void)
{
enum { N = 50 };
int numbers[N];
char *s = "12 13 14 123 1234 12345";
size_t n = 0;
char *p = s;
for ( int value, pos = 0; n < N && sscanf( p, "%d %n", &value, &pos ) == 1; p += pos )
{
numbers[n++] = value;
}
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", numbers[i] );
}
putchar( '\n' );
return 0;
}
The program output is
12 13 14 123 1234 12345
Upvotes: 1
Reputation: 36
You can use strtok
to split string into substrings and then use atoi
to convert that into ints.
#include <stdlib.h>
#include <string.h>
int main()
{
char my_string[] = "12 23 234 2345";
int my_array[50] = {0};
char* token = strtok(my_string, " ");
int i = 0;
while (token)
{
my_array[i] = atoi(token);
token = strtok(NULL, " ");
i++;
}
return 0;
}
Upvotes: 0
Reputation: 57408
The state machine idea is good (albeit overkill; you only have three or four states after all).
You could use both this and Horner's Algorithm to parse the integer.
- set Horner accumulator to 0 and HaveNumber to 0 (false).
- loop:
- read character
- if digit:
- multiply Horner by 10
- add the value of the digit to Horner
- set HaveNumber to 1
- continue
- if HaveNumber:
push Horner onto array
set HaveNumber to 0
- set Horner to 0
- if character was a 0 instead of a space:
break
This does not need memory and does not necessarily use any function call (the digit check may be done verifying the ASCII value of the digit between 0x30 and 0x39)
Upvotes: 0