Debug assertion failed, Expression: (unsigned)(c + 1) <=256 Ask Question c++

235 views Asked by At

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;
1

There are 1 answers

0
Vlad from Moscow On BEST ANSWER

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.