调试断言失败,表达式:(unsigned)(c + 1) <=256 问问题 c++

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

我要统计空格数。据我了解,编译器在这一行发誓 isspace(s[step]) != 0。但是有时候代码启动了也没有报错。不知道为什么会这样

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;

你必须写

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

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

否则通常表达式 s[step] 会产生负值。

这段代码

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

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

可以改写得更简单

size_t number_space = 0;

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

也就是不需要调用strlen而且在循环的条件下