我要计算空格数。据我了解,编译器在这一行发誓 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] != '\0'; i++ )
{
if ( isspace( static_cast<unsigned char>( s[i] ) ) )
{
number_space++;
}
}
那就是没有必要在循环的情况下调用
strlen
。
关于c++ - 调试断言失败,表达式:(unsigned)(c +1)<= 256提问c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493555/