1)我在https://www.tutorialspoint.com/compile_c_online.php上测试了我的代码 它以某种方式通过显示1,3,27,23,19的理想输出工作,但也给我错误消息,这很奇怪,因为所有我的函数没有任何整数.任何人都可以告诉我为什么显示错误的行是错误的?
2)我怀疑它与'未正确处理的角色有关,但我不知道如何打印除%%和之外的所有特殊字符\\.有人可以指引我查看完整列表吗?
编辑:我意识到实际上有2个转义字符我错了(在https://www.geeksforgeeks.org/escape-sequences-c/上找到了正确的术语),这是单引号和双引号.除了这个清单之外还有什么吗?
#include <stdio.h>
int improvedCountWords(const char *str) {
int size=0;
int number=0;
int length=0;
while (str[size]!='\0'){
if (str[size]==' ' || str[size]=='.' || str[size]=='\\' || str[size]=='*' || str[size]=='"'){
if (length>0){
number+=1;
length=0;
}
}
else if (str[size]=='-' || str[size]=="'"){
if (length>0){
length++;
}
}
else{
length++;
}
size++;
}
if (length>0){
number++;
}
return number;
}
int main(){
char s1[]="Panting heavily, he continues his exercises -- grepping, installing new packages, logging in as root, and writing replacements for two-year-old shell scripts in Python.";
char s2[]="\" You'll know why Python is better than Perl... when you try to read your code *six* months from now ...\"";
char s3[]="With Yoda strapped to his back, Luke climbs up one of the many thick vines that grow in the swamp until he reaches the Dagobah statistics lab.";
int x1=improvedCountWords("Python");
int x2=improvedCountWords("Python is AWESOME");
int x3=improvedCountWords(s3);
int x4=improvedCountWords(s1);
int x5=improvedCountWords(s2);
printf("%d,%d,%d,%d,%d",x1,x2,x3,x4,x5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你的指针是"'",而int是比较str[size]中提升的字符值==.这是在这一行,它没有得到妥善处理;
else if (str[size]=='-' || str[size]=="'"){
Run Code Online (Sandbox Code Playgroud)
你可能需要将它与'\''这样比较;
else if (str[size]=='-' || str[size]=='\''){
Run Code Online (Sandbox Code Playgroud)