C++ code to count the total number of spaces in a string:
C++ code example:
#include <iostream>
#include <string>
using namespace std;
int countSpaces(const string& str) {
int spaceCount = 0;
for (char character : str) {
if (character == ' ') {
spaceCount++;
}
}
return spaceCount;
}
int main() {
string inputString;
cout << "Enter a string: ";
getline(cin, inputString);
int spaces = countSpaces(inputString);
cout << "Total number of spaces: " << spaces << endl;
return 0;
}
This program defines a function countSpaces that takes a string as input and iterates through each character, incrementing a counter when it encounters a space. The main function takes user input, calls the countSpaces function, and prints the result.