You have an incorrect algorithm. You count not the number of words, but the number of spaces in the sentence. In addition, the entered string may contain several sentences, and the last sentence may not end with a period. In this case, it is simply ignored. In addition, if the next sentence starts immediately after a period without an intermediate space, then again you will get the wrong result.
The program might look like this:
#include <iostream> int main() { while (true) { const size_t N = 100; char s[N]; std::cout << "\nEnter a sentence (ENter - exit): "; if (!std::cin.getline(s, sizeof(s)) || s[0] == '\0') break; size_t n = 0; for (const char *p = s, *first; *p; ) { while ( *p == ' ' || *p == '\t' ) ++p; if (n == 0) first = p; ++n; while (*p && !(*p == ' ' || *p == '\t' || *p == '.')) ++p; if ( *p == '\0' || *p == '.') { while (*p == '.') ++p; std::cout << "\nThere are " << n << " words in the sentence \""; std::cout.write( first, p - first ) << "\".\n"; n = 0; std::cout << "\nPress a key to continue "; std::cin.get(); } } } return 0; }
Approximate dialogue with the program:
Enter a sentence (ENter - exit): One two. Three four five. There are 2 words in the sentence "One two.". Press a key to continue There are 3 words in the sentence "Three four five.". Press a key to continue Enter a sentence (ENter - exit):