How to determine the number of words in the entered sentence?

    4 answers 4

    On C ++, the operator >> by default omits spaces,

    int n = 0; std::string trash; while (sentence >> trash) n++; 

    therefore, this code at the end of the input will contain the number of words, separated by spaces.

      Run through all the characters of the string if the character is "", increment any variable, when the sentence ends you add another 1, it will be the last word after which there is no space, the variable you increased and will be the desired value.

      • The algorithm is generally incorrect. For example, between words delimiters can still be punctuation marks, and spaces can be more than one in a row. - gecube
      • Then, this is not a valid sentence, in terms of the syntax of the design on the computer. You write after 1 space, and after the punctuation marks you also put a space. - systemiv
      • one
        And who said that the correct sentence will be introduced? Several spaces can easily appear in texts, for example, if indents are required, and the tab character ('\ t') is not used. Yes, and from the space, it is often indistinguishable. - gecube

      Use strtok like strtok or strsep . They are intended for splitting a string into tokens. Select each new token - increment a variable. Just figure out what to use as delimiter characters.

        It is possible through the cycle, to find out the number (i == '' || i == n || i == t) then i ++.

        • In my opinion, the proposed cycle considers the number of letters in a word rather than the number of words in a sentence - gecube
        • It is possible for the loop to see the end of the input of the word and raise the counter to ++, and then after each entered word +1, and specify the completion in # define eof -1, this is the training task. - johnfelix