You have two problems:
cin >> input;
should be std::getline(std::cin, input);
since std::cin
will stop on the first space and not storing the rest of the string.
if (input.substr(0, x) == " ")
I could not understand what you meant by this expression. However, what you want is if (input[x] == ' ')
.
Full Code: (with minor changes)
#include <iostream>
#include <iomanip>
#include <string>
int main(){
unsigned int spaces = 0;
std::string input;
std::getline(std::cin, input);
for (std::size_t x = 0; x < input.length(); x++) {
if (input[x] == ' ') {
spaces++;
}
}
std::cout << spaces << std::endl;
system("pause");
return 0;
}
Online Demo
As @BobTFish mentioed, the right way to do it in real code is:
#include <iostream>
#include <string>
#include <algorithm>
int main(){
std::string input;
std::getline(std::cin, input);
const auto spaces = std::count(input.cbegin(),input.cend(),' ');
std::cout << spaces << std::endl;
system("pause");
return 0;
}
Online Demo