#include <iostream>
#include <windows.h>
usingnamespace std;
int numberOfSpaces;
int getSpaceNumber(string input)
{
// need help here
return numberOfSpaces;
}
int main(void)
{
string input;
cout << "Enter a string with spaces: ";
getline(cin, input);
getSpaceNumber(input);
cout << endl << "Number of spaces: " << numberOfSpaces << endl;
system("pause");
}
Let's say I input this string: "this is a string" I want it to return 3, since there are three spaces in it. Or this: "Hello World", I want that to return 1, since there is one space.
Is there a way to do this? If so please help, thanks a lot!
Examine all the character in the string and keep track of the spaces you find.
If I want to examine the first character in a string I can use:
1 2 3 4 5 6
std::string str;
// ... stuff
if(str[0] == 'z') {} // this checks the 1st character in the string to see if it is a 'z'.
if(str[1] == 'z') {} // this checks the 2nd character in the string to see if it is a 'z'.
You could use that technique to detect all the spaces ' ' in your string and add them up.
You shouldn't check the character at position x, that'll be the character after the last (the terminating \0).
And why did you look for \0 instead of spaces in the first place?
Of course some care needs to be taken with the second define. The first one is harmless, but the second one requires auto support and will conflict with identifiers named foreach if included first.