My code is supposed to count the number of spaces in a given string but right now its counting all the letters up to the first space. I don't know if I'm using a #include <cstring> keyword anywhere thats messing it up or not. I just started learning about strings.
Also, I was wondering if there is another way to set a variable to equal a space (char space = ' ';)
The unsigned int object matches up with the size_t( unsigned int ) which length( ) returns. Without making iLoopunsigned, the compiler should generate a warning, indicating that it's a type mismatch( Microsoft compiler ).
sizeof won't return an appropriate length if I'm not mistaken. Instead, use strlen from cstring.
That sizeof statement is returning the size of the pointer, not the array (which coincidentally is 4 (32-bit pointer) / 1 (8-bit character) which is 4).
#include <iostream>
#include <cstring>
usingnamespace std;
int count( char str[] )
{
int iSpaces = 0;
//Forgot to mention that strlen is incredibly ineffecient... store ahead of time.
int strSize = strlen(str);
for(unsignedint iLoop = 0; iLoop < strSize; iLoop++ )
if(str [iLoop] == ' ' )
iSpaces++;
return iSpaces;
}
int main()
{
char str[100] = "\0";
cout << "Enter text: ";
cin.getline( str, 100 );
int numSpaces = count( str );
cout << "Number of spaces: " << numSpaces << endl;
cin.ignore();
return 0;
}
C-strings are far from deprecated however most C++ users won't recommend there use. I agree with this. I don't necessarily agree to use std::string but since that's in our immediate library, I can say it's safe to use std::string over c-strings. I honestly don't like the idea of a null-terminated string...
As far as why sizeof didn't work, it's because it's a compile-time directive. It also has no way of knowing whether what you passed is an array or a pointer so it assumes pointer (for various reasons). Even if it was an array, it wouldn't be able to determine the size.
#include <iostream>
#include <string>
int count( const std::string& input )
{
int iSpaces = 0;
for (int i = 0; i < input.size(); ++i)
if (input[i] == ' ') ++iSpaces;
return iSpaces;
}
int main()
{
std::string input;
std::cout << "Enter text: ";
std::getline( std::cin, input );
int numSpaces = count( input );
std::cout << "Number of spaces: " << numSpaces << std::endl;
std::cin.ignore();
return 0;
}
EDIT: You seem to be uncertain on whether or not to use C strings or std::string. There are answers to such questions but they bring more questions. As a matter of fact, I've recently started the quest on finding my preferred string library.