为什么我在尝试计算字符串字母数的程序中收到此错误?

调试断言失败! 程序:… Laske aakkoset \ Debug \Ohjelmontitehtävä4.1Laske aakkoset.exe文件:minkernel \ crts \ ucrt \ appcrt \ convert \ isctype.cpp

Line: 36 Expression: c >= -1 && c <= 255

我的代码:

 #include  #include  int count_alpha(const char *str) { int i = 0; int j = 0; while (*str) { if (isalpha(str[j])) { i++; j++; str++; } else { i = i; j++; str++; } } printf("%d", i); return (0); } int main(void) { char lol[] = "asdf"; count_alpha(lol); } 

你增加char *指针和索引; 但你只需要做一个。 它可以非常简单地编辑为:

 while (str[j]) { if (isalpha(str[j])) i++; ++j; } 

要么

 while (*str) { if (isalpha(*str)) i++; ++str; } 

尝试增加两者将导致奇数长度的未定义行为,因为您将开始读取尚未分配给程序的内存。

简化! 这是一个有效的C程序。 问题中没有任何内容暗示C ++。

 #include  #include  int count_alpha(const char *str) { int count = 0; while (*str) { if (isalpha(*str)) { ++count; } ++str; } printf("%d", count); return count; } int main(void) { char lol[] = "asdf"; count_alpha(lol); } 

这是一个更多的C ++ ish版本。

 #include  #include  #include  int count_alpha(const std::string_view str) { int count = 0; for(auto c: str) { if (isalpha(*str)) { ++count; } } std::cout << count << std::endl; return count; } int main(void) { char lol[] = "asdf"; count_alpha(lol); } 

这是另一个不使用string_view的C ++版本:

 #include  #include  #include  template size_t count_alpha(const T &str) { size_t count = std::count_if(std::begin(str), std::end(str), std::isalpha); std::cout << count << std::endl; return count; } int main(void) { char lol[] = "asdf"; count_alpha(lol); }