简体   繁体   中英

How to find out how many words are in each line?

Say you have a text file filled with sentences. For example:

hey how are you
you good?
nice to meet you jeff

I'm writing a program to print things out depending on how many indexes are on each line but I cant wrap my head around how to find how many words on each line. How could I go about counting how many words are on each line?

for (int i=0; i < wordle->leng; i++) {
    printf ("%s ", wordle->allwords[i]);

This is my print function for the program. leng is how many lines so it knows how many times to repeat.

Some of the lines have 5 words, some 3, and it isn't printing in the correct format. Also not all lines will end with punctuation.

The POSIX getline() function is very useful for that; it reads line from stream until EOL. So you can read with that line by line and the you could make a loop that adds 1 to int word_count = 0; every time you read something that is not a whitespace and the previous char before that was whitespace (but you have to make additional logic for initial word).

You can use fgets() if you don't have getline() available, but it doesn't expand the buffer to deal with extra long lines, unlike getline() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM