【发布时间】:2021-08-11 03:37:11
【问题描述】:
代码:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char filename[] = "11.txt";
char filename1[] = "2.txt";
FILE *ptr, *resultptr;
char string[100];
char words[100][100];
int len = sizeof(filename) / sizeof(char);
int i = 0, j = 0, k, length, count;
int main()
{
fopen_s(&ptr, filename, "r");
fopen_s(&resultptr, filename1, "w");
if ((ptr == nullptr) || (resultptr == nullptr)) {
printf("Files were not opened!");
return -1;
}
while (fgets(string, sizeof string, ptr)) {
for (k = 0; string[k] != '\0'; k++) {
if (string[k] != ' ' && string[k] != '\n') {
words[i][j++] = tolower(string[k]);
} else {
words[i][j] = '\0';
i++;
j = 0;
}
}
length = i + !!j;
fputs("Occurrences of each word:\n", resultptr); //prints this sentence into file
for (i = 0; i < length; i++) {
if (strcmp(words[i], "0") == 0)
continue;
count = 1;
char *ch = words[i];
for (j = i + 1; j < length; j++) {
if (strcmp(words[i], words[j]) == 0 && (strcmp(words[j], "0") != 0)) {
count++;
strcpy_s(words[j], "0");
}
}
fputs("The word ", resultptr);
if (string[i] != ' ' && string[i] != '\n') {
fprintf(resultptr, "%s", ch);
}
fputs(" occurred ", resultptr);
fprintf(resultptr, "%d", count);
fputs(" times\n", resultptr);
}
fclose(ptr);
fclose(resultptr);
return 0;
}
}
计数部分工作得非常好,但问题是当我尝试打印结果时,对于句子“to be or not: to be that is the question ...”它会打印:
Occurrences of each word:
The word to occurred 2 times
The word be occurred 2 times
The word occurred 1 times
The word not: occurred 1 times
The word that occurred 1 times
The word is occurred 1 times
The word occurred 1 times
Occurrences of each word:
The word to occurred 1 times
The word be occurred 1 times
The word or occurred 1 times
The word occurred 1 times
The word that occurred 1 times
The word is occurred 1 times
The word occurred 2 times
The word question occurred 1 times
The word ... occurred 1 times
怎么了?就像我不专业,但有人可以指导我这里有什么问题吗?和原来的有点变化,但还是有很多错误
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。
-
请不要以使现有答案无效的方式更改问题。我已回滚您最近的编辑。如果您想使用后续问题更新您的问题,则可以将其添加到问题的底部。只要原始问题保持不变,这不会使现有答案无效。
-
@Youngwildandfree:您可以通过单击分数下方的灰色复选标记来接受其中一个答案。