【发布时间】:2021-12-13 23:04:19
【问题描述】:
我正在尝试使用此自定义函数计算用户输入的字符串中的单词数:
int count_words(char* text)
{
int wc = 0;
for(int i = 0,k = strlen(text); i<k;i++)
{
if(strcmp(" ",text[i]) ==0 || strcmp(".",text[i]) ==0 || strcmp("!",text[i]) ==0 || strcmp("?",text[i]) ==0 || strcmp(",",text[i]) ==0)
{
wc++;
}
}
return wc+1;
}
但我不断收到此错误:
re.c:59:21: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
if(strcmp(" ",text[i]) ==0 || strcmp(".",text[i]) ==0 || strcmp("!",text[i]) ==0 || strcmp("?",text[i]) ==0 || strcmp(",",text[i]) ==0)
^~~~~~~
&
re.c:59:48: error: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'; take the address with & [-Werror,-Wint-conversion]
if(strcmp(" ",text[i]) ==0 || strcmp(".",text[i]) ==0 || strcmp("!",text[i]) ==0 || strcmp("?",text[i]) ==0 || strcmp(",",text[i]) ==0)
^~~~~~~
&
到底发生了什么?
【问题讨论】:
-
text[i]的数据类型是char,但是strcmp需要两个const char *,所以你想通过text + i或等效的&text[i],正如编译器确实建议的那样你。 -
无论如何,看起来您只是在比较单个字符的字符串,因此您不妨手动检查
text[i] == ' ' || text[i] == '.' || ...。您的strcmp将始终失败,除非该字符是字符串的最后一个字符,因为strcmp会检查 整个 两个字符串是否相等。
标签: c split c-strings function-definition