Yes, there are often questions (most likely training questions) in which you need to pull out words (or numbers) separated from each other by various separators from a file (or lines) and then do something with them (in your case, determine the length and count the number of with a length of 3).
Here is a very simple little function that selects the next word from the line and allows you to simplify the solution to the mass of similar problems.
#include <stdio.h> #include <string.h> /* before call: *p -- ptr to start search WORD in delimiters after call: *p -- ptr to next char after word (and *p - word == WORD length) returns ptr to WORD or 0 */ char * strtos (char **p, const char *delim) { char *word = 0; if (*((*p) += strspn(*p, delim))) { word = *p; (*p) += strcspn(*p, delim); } return word; }
To understand how it works, just read man strspn .
How you can use it (Linux, file c1.c)
(I apologize, I messed up a bit (inattentively read the question), in your case you only need an internal cycle, after which you print the meter and discard it, and you can consider the external one as a test strapping)
#include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { // предполагаем, что strtos оттранслирована gcc -c strtos.c #endif // по хорошему все это д.б. в каком-нибудь подключаемом strtos.h файле char *strtos (char **start_lookup, const char *delimiters_str); #ifdef __cplusplus }; #endif #define SEP " ,\n" // допустим, что слово все же не может переходить со строки на строку //#define SEP " \t\n\"\'.,;:+-*/(){}[]=?!~%^&\\" // а это для Си текстов (наверняка что-то упустил) int main (int ac, char *av[]) { size_t lsize, wlen, n3 = 0; char *curline = 0, *start, *word; while ((getline(&curline, &lsize, stdin) > 0) && (start = curline)) while (word = strtos(&start, SEP)) n3 += (start - word == 3); return printf("%ld 3-length words\n", (long)n3) < 0; }
Those. read the file line by line, alternately pull out words (separated by one or more separators (space, comma)) from the read line, and if the word length is three, increment the counter.
We broadcast and run
avp@avp-ubu1:hashcode$ g++ c1.c strtos.o ; ./a.out <c1.c 7 3-length words avp@avp-ubu1:hashcode$
If something is not clear, ask in the comments (mentioning @avp, I won't get a notification without a dog).