Why it would not go?
my prog needs to sum the num of letters |
In other words, you want to print the length of each word in the string?
Lets look at your code again. I'll copy it here and use code tags (you should too) and indent to my liking:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void countletters( char* s )
{
int cword = 0;
int size = strlen(s) + 2;
for( int i=0; i<=size; i++ )
{
cword++;
if ( (int)s[i]==32 || (int)s[i]==0 )
{
cout << cword-1 <<' ';
continue;
}
}
}
|
You don't reset the cword, so after the loop the value of cword == size. The "Good luck" ougth to print "4 9 ".
A C-string is terminated by null character. The strlen() returns the count of characters before the null. The character array does not need to have any more elements than strlen()+1. Your loop dereferences elements strlen()+2 and strlen()+3, which could be an out-of-range error (luckily you don't write to them), and definitely breaks the logic, because the program will report (undefined) word-lengths that are not part of the assumed input.
Please, explain the purpose.
The explicit casts to int on line 8 are unnecessary, because they will occur implicitly (and from documentation point every programmer should know about implicit char->int cast). Furthermore, you are using C-style cast syntax. Please avoid it. The C++ has a more precise
static_cast<int>( s[i] )
.
What if there are more than one space between consecutive words? What if there is some other whitespace (tab, newline) in the string.