gpt4 book ai didi

计算最长单词中的字母数

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:42 24 4
gpt4 key购买 nike

我想得到最长单词的字母数。如果我输入类似“hello me”的内容,我会得到 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;
}

最佳答案

最简单的调试方法之一是打印您获得的数据,以确保程序获得了您认为获得的数据。

scanf() , %s格式读取单个“单词”,停在第一个空白处。如果你打印了 f在调用 scanf() 后立即:

printf("Input: <<%s>>\n", f);

您会看到它只包含“联盟”,所以它正确地给出了 6。严格来说,你应该检查 scanf()在使用它之前实际上得到了一些输入:

if (scanf("%99s", f) != 1)
…EOF or error…

你要么需要使用 fgets()阅读整行,或调用 scanf()longest_word()迭代以获得“传说”和答案 7。请注意,您的代码会将换行符(例如 fgets() 保留在行尾)作为单词的一部分。您可能需要检查 <ctype.h> header 并使用 isspace()用于测试空白的宏。

此外,正如 pablo1977 首次指出的那样在他的 answer , 你需要初始化 maxlongest_word() .

关于计算最长单词中的字母数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24275670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com