1

I want to count the number of spaces. As I understand it, compiler sweare at this line isspace(s[step]) != 0. But sometimes the code started and there was no error. I don't know why it is so.

char s[] = "So she was considering";

int number_space = 0, step = 0;
int length_string = strlen(s);

while(strlen(s) != step){
    if(isspace(s[step]) != 0){ 
        number_space++;
    }
step++;
}

cout << number_space;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
A.Kross
  • 165
  • 8
  • Try `while ( step < length_string )` … Also, when the debug assertion message shows up, does it show in your code where it happens? – ChrisMM Dec 26 '19 at 21:20
  • `char` is normally signed and the “ctype” functions require a non-negative argument (or `EOF`). Try casting the argument to `unsigned char`. – Dietmar Kühl Dec 26 '19 at 21:25
  • Unrelated, `std::count_if` solves most of this for you, just feed it a decent predicate function. – WhozCraig Dec 26 '19 at 21:35

1 Answers1

1

You have to write

if ( isspace( static_cast<unsigned char>( s[step] ) ) != 0 ){ 

or

if ( isspace( ( unsigned char )s[step] ) != 0 ){ 

Otherwise in general the expression s[step] can yield a negative value.

This code snippet

int number_space = 0, step = 0;
int length_string = strlen(s);

while(strlen(s) != step){
    if(isspace(s[step]) != 0){ 
        number_space++;
    }
step++;
}

can be rewritten more simpler

size_t number_space = 0;

for ( size_t i = 0; s[i] != '\0'; i++ )
{
    if ( isspace( static_cast<unsigned char>( s[i] ) ) )
    {
        number_space++;
    } 
}   

That is there is no need to call strlen and moreover in the condition of the loop.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335