【发布时间】:2020-09-07 00:55:18
【问题描述】:
我正在尝试使用标准 C 函数编写一个接收文件和字符串的程序,该程序计算字符串包含的文件中的所有字符。
例如,如果用户写:
counter.exe x.txt abcd
程序计算文件x.txt中字符串包含的每个字符的个数:a, b ,c ,d
示例消息:
Number of 'a' characters in 'x.txt' file is: 12
Number of 'b' characters in 'x.txt' file is: 0
Number of 'c' characters in 'x.txt' file is: 3
Number of 'd' characters in 'x.txt' file is: 5
到目前为止,我已经能够让它打印并计算文件中的一个字符,我如何让它计算我告诉它计算的所有字符,而不仅仅是字符串中的第一个字符?
counter.c代码:
#include<stdio.h>
int main() {
int count = 0;
char sf[20]; char rr; FILE* fp; char c;
printf("Enter the file name :\n");
gets(sf);
printf("Enter the character to be counted :\n");
scanf("%c", &rr);
fp = fopen(sf, "r");
while ((c = fgetc(fp)) != EOF)
{
if (c == rr)
count++;
}
printf("File '%s' has %d instances of letter '%c'.", sf, count, rr);
fclose(fp);
return 0;
}
【问题讨论】:
-
这很可能是之前的家庭作业,当然,但是你为这个做了什么尝试?
-
您为运行程序而指定的行肯定不适用于此代码,因为您在程序开始时没有任何输入。请参阅此处为您的主要功能提供一些输入:stackoverflow.com/q/498320/7758765