I am trying to loop through an array that contains a string with is several words separated by spaces. Ultimately I want to make each word within the string a new variable so I can compare it to other variables.
My approach is to loop though assigning that index of the array to another array until I hit a space where it then starts a new loop starting off where the other one fished again storing to another array. This doesn't seem to be working for me.
What is the simplest way of doing this? I am very new to this so the simpler the better. I've attached what I've tried so far.
#include <stdio.h>
int main(){
char input[100];
char order1[20];
char order2[20];
char order3[20];
char order4[20];
char space = ' ';
int counter = 0;
//input is an order that is separated by spaces
fgets(input, 100, stdin);
printf("The order is: %s \n", input);
for(int i; i<20; i++){
printf("%c \n", input[i]);
}
for(int i=counter; i<100; i++) {
if(input[i] == space){
break;
}
else {
order1[12] += input[i];
}
}
for(int j=counter; j<100; j++) {
if(input[j] == space){
break;
}
else {
order2[12] += input[j];
}
}
for(int k=counter; k<100; k++) {
if(input[k] == space){
break;
}
else {
order3[12] += input[k];
}
}
for(int l=counter; l<100; l++) {
if(input[l] == space){
break;
}
else {
order4[12] += input[l];
}
}
printf("Order 1: %s \n", order1);
printf("Order 2: %s \n", order2);
printf("Order 3: %s \n", order3);
printf("Order 4: %s", order4);
return 0;
return 0;
}
If I understood correctly, the problem is to split the string at spaces and store those tokens in a separate string.
If this is the case, one might ask what utility the following construct has:
Since you're not doing anything else with the array
order1(except printing), the problem is that 19 out of 20 characters are uninitialized and the value at offset 12 is most likely not what you expect.First, we get rid of the magic numbers and define meaningful symbols
but instead of single variables it would be better if we had an array of strings, therefore
we now have an array of array of char or in other words, a list of orders, where each order has a specific length.
Let's fill them up: