#include <iostream> #include <cstring> using namespace std; int main(){ char s[250]; int count = 0; cin >> s; for(int i(0);i < strlen(s);i++){ if (s[i] == ' '){ count++; } } cout << count+1 << endl; return 0; } 

For some reason, does not count the number of words. Always 0. Tell me what to fix?

  • You have cin >> s only before the first space copies the entered string in s . - Vladimir Gamalyan
  • @VladimirGamalian, and how to make for many lines? While loop? - goodalien

1 answer 1

The reason is that cin >> s; copies the entered string to s only up to the first space, respectively, no further spaces are found.

To enter a string with spaces, you can use the function std::getline , and accept the entered string immediately in std::string . Then you will not have to fear the buffer overflow s[250] :

 std::string s; std::getline(std::cin, s); 

To bypass the string, you can use the range version of the loop:

 for (auto c : s) if (c == ' ') count++; 

But it is even easier to use the standard function std :: count . The final option:

 #include <iostream> #include <string> #include <algorithm> int main() { std::string s; std::getline(std::cin, s); size_t count = std::count(s.begin(), s.end(), ' '); std::cout << count << std::endl; } 

Link to valid code.