Ozymandias Ozymandias - 1 month ago 9
C++ Question

Counting blank spaces using an incrimenter

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string> using namespace std;

using namespace std;

int main()
{
int spaces = 0;
string input;
cin >> input;

for (int x = 0; x < input.length(); x++) {
if (input.substr(0, x) == " ") {
spaces++;
}
}
cout << spaces << endl;
system("pause");
return 0;
}


I'm trying to make a simple program that counts the number of spaces by adding to an incrementer.

It always returns 0 for some reason.

Answer

You have two problems:

  1. 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.
  2. 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