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.
cin >> sonly before the first space copies the entered string ins. - Vladimir Gamalyan