How to count white spaces in a string

I'm trying to figure out how to count the white spaces in a string. So far I've managed to come up with the following code.

#include <iostream>
#include <string>
#include <locale>

using namespace std;

int main() {

// Ask user to input a string and tell them what they put down
string str1;
cout << "Please enter your text : ";
getline(cin, str1);
cout << "Your input was : " << str1;

//Checking for white spaces inside the string
for (int i = 0; i < str1.length(); i++){
if (isspace(str1.at(i))) {

}
}
// Prints out the amount of spaces inside the string.
cout << "\nThe number of 'spaces(s)' : " << str1;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <locale>

int main()
{

    // Ask user to input a string and tell them what they put down
    std::string str1;
    std::cout << "Please enter your text : ";
    std::getline( std::cin, str1 );
    std::cout << "Your input was : '" << str1 << "'\n'" ;

    std::size_t num_whitespaces = 0 ; // count of white space characters

    //Checking for white spaces inside the string
    // http://www.stroustrup.com/C++11FAQ.html#for
    for( char c : str1 ) // for each character in the string
    {
        // http://en.cppreference.com/w/cpp/locale/isspace
        // use the locale used by stdin
        if( std::isspace( c, std::cin.getloc() ) ) ++num_whitespaces ;

        // or use  current C locale: #include <cctype> and
        // if( std::isspace(c) ) ++num_whitespaces ;
    }

    // Prints out the amount of spaces inside the string.
    std::cout << "\nThe number of 'space(s)' : " << num_whitespaces << '\n' ;
}
You were pretty close. You just need to count the whitespace when you loop through the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <locale>

using namespace std;

int main() 
{

  // Ask user to input a string and tell them what they put down
  string str1;
  cout << "Please enter your text : ";
  getline(cin, str1);
  cout << "Your input was : " << str1;

  //Checking for white spaces inside the string
  int count = 0;
  for (int i = 0; i < str1.length(); i++)
  {
    if (isspace(str1.at(i))) 
    {
      count++;
    }
  }
  // Prints out the amount of spaces inside the string.
  cout << "\nThe number of 'spaces(s)' : " << count << "\n\n;
  system("PAUSE");
  return 0;
}
 
Thank you so much for the help! I appreciate it.
Topic archived. No new replies allowed.