I'm trying to allow the following
Assume program is running and it's time for input:
hello word
The program then needs to take this input and for each word perform a search, breaking up that line into "hello," and "world." I'm having trouble coming up with a decent way to do this. I've tried using a 2d array, but it's just getting me deep into segfaults. Another idea I had was to do something like:
get line from stdin as a char*
then pass that string to another function that takes the string and its current index:
get character from string at index,
while character is not a ' ' or '\n' add it to a char[buffer].
inc index, get another character.
return strdup(word);
This requires me to make the integer a pointer however, since I'm only returning the word. That way the index can be updated in main so that when its time to get the next word, the main string knows where it left off. My implementation of this is horrid, however, and is producing segfaults as well.
I'll post my code below, but does anyone have any other ideas?
Code:
char* get_query()
{
char query[QUERY_LENGTH*QUERY_LIMIT];
int index = 0;
char c;
while( (c = getchar()) != '\n')
query[index++] = c;
query[index] = '\0';
return strdup(query);
}
char* get_next_query(char* queries, int* index)
{
char c;
int i = 0;
char word[BUFFER];
//printf("Index came in as : %d \n", index);
//printf("Char at index in query is: %c \n", queries[index]);
while(queries[*index] != ' ' || queries[*index] != '\n')
{
//printf("Queries[index] = %d %c \n", *index, queries[*index++]);
word[i++] = queries[index++]; //segfaults
}
word[i] = '\0';
return strdup(word);
}