0

Is it possible to use fgets() to save different words divided by whitespace and then find each word?

For example let's say I have this:

char words[100];
fgets(words,100,stdin);

and then I have to find each word to use it in the rest of my program. How can I do that?

Jaroslav Kadlec
  • 2,505
  • 4
  • 32
  • 43
Harr Tou
  • 41
  • 2
  • 9
  • 1
    possible duplicate of [Split string in C every white space](http://stackoverflow.com/questions/4513316/split-string-in-c-every-white-space) – 5gon12eder May 19 '15 at 23:15
  • What have you tried? Looks like you need to loop through the array looking for space char. – Andy Joiner May 19 '15 at 23:16

2 Answers2

3

You can use strtok_r or you could use the pcre library if you want to do things with regex.

char *save_ptr;
char *word = strtok_r(words, " \t", save_ptr);

and then repeated other calls to

word = strtok_r(words, " \t", save_ptr);

until word == NULL

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
2

fgets() will save your input into a string. To divide it into individual words, you can either go through the string (possibly using isalpha() and similar), or use strtok() to get individual words.

che
  • 12,097
  • 7
  • 42
  • 71