#include <stdio.h> #include <string.h> #define MAX_LENGTH 100 char* findLongestCommonWord(char* sentence1, char* sentence2) { char* longestWord = ""; char* word; char* token1 = strtok(sentence1, " "); while (token1 != NULL) { char* token2 = strtok(sentence2, " "); while (token2 != NULL) { if (strcmp(token1, token2) == 0 && strlen(token1) > strlen(longestWord)) { longestWord = token1; } token2 = strtok(NULL, " "); } token1 = strtok(NULL, " "); } return longestWord; } int main() { char sentence1[MAX_LENGTH]; char sentence2[MAX_LENGTH]; printf("请输入第一个句子:"); fgets(sentence1, sizeof(sentence1), stdin); printf("请输入第二个句子:"); fgets(sentence2, sizeof(sentence2), stdin); // 去除换行符 sentence1[strcspn(sentence1, "\n")] = 0; sentence2[strcspn(sentence2, "\n")] = 0; char* longestCommonWord = findLongestCommonWord(sentence1, sentence2); printf("最长公共单词是:%s\n", longestCommonWord); return 0; } 这段代码在devc++上运行结果错误
时间: 2024-04-09 22:29:22 浏览: 155
在 Dev-C++ 上运行结果错误的问题可能是因为 `strtok` 函数在多次调用时需要使用 `NULL` 作为第一个参数。在您的代码中,第二个 `strtok` 循环没有重置 `sentence2`,导致无法正确分割第二个句子中的单词。为了解决这个问题,您可以在第一个 `while` 循环结束后重新将 `sentence2` 赋值给 `token2`,以重新开始分割第二个句子的单词。
下面是修改后的代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
char* findLongestCommonWord(char* sentence1, char* sentence2) {
char* longestWord = "";
char* word;
char* token1 = strtok(sentence1, " ");
while (token1 != NULL) {
char* token2 = strtok(sentence2, " ");
while (token2 != NULL) {
if (strcmp(token1, token2) == 0 && strlen(token1) > strlen(longestWord)) {
longestWord = token1;
}
token2 = strtok(NULL, " ");
}
token1 = strtok(NULL, " ");
// 重新将sentence2赋值给token2
sentence2 = strdup(sentence2);
}
return longestWord;
}
int main() {
char sentence1[MAX_LENGTH];
char sentence2[MAX_LENGTH];
printf("请输入第一个句子:");
fgets(sentence1, sizeof(sentence1), stdin);
printf("请输入第二个句子:");
fgets(sentence2, sizeof(sentence2), stdin);
// 去除换行符
sentence1[strcspn(sentence1, "\n")] = 0;
sentence2[strcspn(sentence2, "\n")] = 0;
char* longestCommonWord = findLongestCommonWord(sentence1, sentence2);
printf("最长公共单词是:%s\n", longestCommonWord);
return 0;
}
```
请尝试使用修改后的代码,并重新运行程序,看看是否能够得到正确的结果。如果还有其他问题,请随时提问。
阅读全文