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;
}
答案 0 :(得分:6)
您的指针为"'"
,而int是str[size]
比较中提升的==
中的字符值。它在这一行并且没有得到妥善处理;
else if (str[size]=='-' || str[size]=="'"){
您可能需要将其与此'\''
进行比较;
else if (str[size]=='-' || str[size]=='\''){
答案 1 :(得分:1)
str[size]
是一个字符,您将其与字符串文字进行比较 - "'"
[编译器必须在此语句上发出警告] 。由于您希望将字符串str
的字符与单引号'
进行比较,因此您需要将其转义以使其不代表自身。使用转义字符\
来执行此操作。因此它应该是:
str[size]=='\''
来自C标准#6.4.4.4p3
单引号&#39;,双引号&#34;,问号?,反斜杠\和任意整数值可根据下表的转义序列表示:
single quote ' \'
double quote " \"
question mark ? \?
backslash \ \\
octal character \octal digits
hexadecimal character \x hexadecimal digits