我想得到最长字的字母数.如果我输入像"你好我"这样的东西,我会得到5分,但如果我写一些更长的东西,比如"英雄联盟",我会得到6而不是7.为什么?
#include <stdio.h>
int longest_word(const char string[]){
int i;
int max;
int cont;
i=0;
while(string[i]!='\0'){
for(cont=0;string[i]!=' '&& string[i]!='\0';i++)
cont++;
if (cont>max)
max=cont;
++i;
}
return max;
}
int main(void){
char f[100]; #maybe this is the problem?
int i;
printf("input a string: ");
scanf("%s",f);
i=longest_word(f);
printf("%d",i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
最简单的调试方法之一是打印您获得的数据,以确保程序得到您认为的程序.
使用时scanf(),%s格式会读取单个"单词",在第一个空格处停止.如果您f在致电后立即打印scanf():
printf("Input: <<%s>>\n", f);
Run Code Online (Sandbox Code Playgroud)
你会发现它只包含'联盟'所以它正确地给出了6.严格来说,scanf()在使用它之前,你应该检查一下是否有一些输入:
if (scanf("%99s", f) != 1)
…EOF or error…
Run Code Online (Sandbox Code Playgroud)
您可能需要使用fgets()读取整行,或者调用scanf()并longest_word()迭代地获取"图例"和答案7.请注意,您的代码将计算换行符(例如保留在行的末尾fgets())作为一个词的一部分.您可能需要检查<ctype.h>标题并使用isspace()宏来测试空白区域.
此外,作为第一所指出的pablo1977在他的答案,你需要初始化max中longest_word().