输入一个字符串,统计其中最长的单词并输出。 #include <stdio.h> int findLongest( char str[] ); int main() { char sArr[100] = { 0 }; int loc, i; gets(sArr); loc = findLongest(sArr) ; for (i = loc; sArr[i] != ' ' && sArr[i] != '\0'; i++) putchar(sArr[i]); return 0; } int findLongest( char str[] ) { int i = 0, Loc = 0, len = 0, lLoc = 0; while (str[i] != '\0') { while (str[i] == ' ') i++; lLoc = i; while (str[i] != ' ' && str[i] != '\0') ; if (i -lLoc > len) { ; Loc = lLoc; } } ; } ###输入样例 This is a C Program ###输出样例 Program
时间: 2024-02-14 18:15:35 浏览: 102
输出样例应该是 "Program" 而不是 "Program ",最后的空格不应该输出。另外,findLongest函数中缺少返回值,需要将最长单词的起始位置Loc返回给主函数。下面是修改后的代码:
```
#include <stdio.h>
int findLongest(char str[]);
int main()
{
char sArr[100] = {0};
int loc, i;
gets(sArr);
loc = findLongest(sArr);
for (i = loc; sArr[i] != ' ' && sArr[i] != '\0'; i++)
putchar(sArr[i]);
return 0;
}
int findLongest(char str[])
{
int i = 0, Loc = 0, len = 0, lLoc = 0;
while (str[i] != '\0')
{
while (str[i] == ' ')
i++;
lLoc = i;
while (str[i] != ' ' && str[i] != '\0')
i++;
if (i - lLoc > len)
{
len = i - lLoc;
Loc = lLoc;
}
}
return Loc;
}
```
阅读全文