我正在尝试编写一个程序,它打开一个文本文件,从文件中读取,将大写更改为小写,然后计算该单词在文件中出现的次数并将结果打印到新的文本文件中。
到目前为止,我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
int main()
{
FILE *fileIN;
FILE *fileOUT;
char str[255];
char c;
int i = 0;
fileIN = fopen ("input.txt", "r");
fileOUT = fopen ("output.txt", "w");
if (fileIN == NULL || fileOUT == NULL)
{
printf("Error opening files\n");
}
else
{
while(! feof(fileIN)) //reading and writing loop
{
fscanf(fileIN, "%s", str); //reading file
i = 0;
c = str[i];
if (isupper(c)) //changing any upper case to lower case
{
c =(tolower(c));
str[i] = putchar(c);
}
printf("%s ", str); //printing output
fprintf(fileOUT, "%s\n", str); //printing into file
}
fclose(fileIN);
fclose(fileOUT);
}
getch();
}
input.txt文件包含以下“西班牙的雨主要落在飞机上”不要问为什么。程序运行后的输出如下所示:西班牙的雨主要落在飞机上
我设法将大写单词小写。我现在无法理解如何计算每个单词的出现次数。例如,在输出中,我希望它说“the 2”,意思是 2 出现了,这也意味着我不想再将“the”存储在该文件中。
我在想 strcmp 和 strcpy 但不确定如何以我想要的方式使用它们。
帮助将不胜感激
(如果格式不好,请见谅)