+ 1

Turning program into reusable function in C help???

https://code.sololearn.com/cR0VbZRJ37G7 I would like to change the following into a reusable function that accepts a string and returns a multidimensional array of word strings. Any help is greatly appreciated. Specifically what does the function declaration look like and then a main below it that gets the string as input and prints the words maybe??? #include <stdio.h> #include <string.h> int main(){ char input[200], word[20][20]; int inputLength, i, j = 0, wc = 0; fgets(input, 200, stdin); inputLength = strlen(input); for (i = 0; i <= inputLength; i++){ if (input[i] == ' ' || input[i] == '\0') { word[wc][j] = '\0'; j = 0; wc++; } else { word[wc][j] = input[i]; j++; } } printf("Original sentence: %s\n", input); for(i = 0; i < wc; i++){ printf("Word %d: %s\n", i + 1, word[i]); } return 0; }

8th Jan 2020, 12:28 AM
Shay Christensen
Shay Christensen - avatar
2 Réponses
+ 1
I took an interest in this and gave it a try. The split() function modifies the word array passed in argument (because arrays in C are passed to a function as a pointer to the first element). The word count is returned, so we have right upper limit in the printing loop. https://code.sololearn.com/cJH9W3J7BUSd/?ref=app
8th Jan 2020, 2:59 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Do you hear about strtok function in <string.h>? It allow to split a sentance into separate words. https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm
8th Jan 2020, 2:44 PM
Jegors Čemisovs
Jegors Čemisovs - avatar