#include <stdio.h>
int main() {
FILE *fb;
char data[255];
int c=0;
int count[75] = {0};
fb = fopen("Input.txt", "r");
fgets(data, 255, fb);
/* Start finding frequency*/
while (data[c] != '\0')
{
if( data[c] >= '0' && data[c] <= 'z')
count[data[c] - 'a']++;
c++;
}
for (c = 0; c < 75; c++)
{
/** Printing only those characters
whose count is at least 1 */
if (count[c] != 0)
printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
}
return 0;
}
示例输入文件:&#34; Fred Fish 12345678&#34;
我能够处理输入文件中的空格,但程序不会读取大写字母的频率和数字字符。我可以在程序中更改什么有助于解决问题。阅读freq后,我的计划是保存文件,以便我可以使用HUffman进行压缩
答案 0 :(得分:0)
我猜测代码
count[data[c] - 'a']++;
到
count[data[c] - '0']++;
如果数据[c]小于75,则计数[data [c] - 'a']不起作用
答案 1 :(得分:0)
#include <stdio.h>
int main() {
FILE *fb;
char data[255];
int c = 0;
int count[75] = { 0 };
fb = fopen("Input.txt", "r");
fgets(data, 255, fb);
/* Start finding frequency*/
while (data[c] != '\0')
{
if (data[c] >= 'a' && data[c] <= 'z') // here you check normal letters
count[data[c] - 'a']++;
else if (data[c] >= 'A' && data[c] <= 'Z')
count[data[c] - 'A' + 26]++; // Capital letters will be stored after lower cases
else if (data[c] >= '0' && data[c] <= '9')
count[data[c] - '0' + 51]++; // Numbers will be stored after capital letters
c++;
}
// count[] is initialized as following :
// From count[0] to count[25] == Occurence of low case characters
// From count[26] to count[51] == Occurence of capital characters
// From count[52] to count[61] == Occurence of numbers from 0 to 9
for (c = 0; c < 61; c++)
{
/** Printing only those characters
whose count is at least 1 */
if (count[c] != 0) {
if (c < 26)
printf("%c occurs %d times in the entered string.\n", c + 'a', count[c]);
// Starting from 'a', iterating until 'z'
else if (c < 52)
printf("%c occurs %d times in the entered string.\n", c + 'A' - 26, count[c]);
// Same as for low case characters
// Substracting 26 because we already have iterated through the first 26 low case characters
// Starting from 'A' until 'Z'
else if (c >= 52)
printf("%c occurs %d times in the entered string.\n", c + '0' - 51, count[c]);
// Same as for characters
// Substracting 51 because we already have iterated through low cases and capital characters
// Starting from '0' until '9'
}
}
return 0;
}
问题在于,考虑到ascii table,您通过减去等于{{1}的count
将数字和数字存储在数组'a'
的负数中在ASCII中。这应该工作,但我无法测试它,所以要小心它。
对于打印,我们对小写字符,然后是大写字符和数字做同样的事情:我们从第一个开始:97
,然后是'a'
,然后是'A'
,迭代直到最后一个使用c并打印它们。我们使用C,'0'
,'a' + 1 = 'b'
等
对于输入'A' + 1 = 'B'
,此代码的输出为:
Fred Fish 12345678
答案 2 :(得分:0)
您应该修改代码中的'a'
到'0'
,以便考虑所有大写字母和数字。
#include <stdio.h>
int main() {
...
/* snippet */
...
while (data[c] != '\0')
{
if( data[c] >= '0' && data[c] <= 'z')
count[data[c] - '0']++;
c++;
}
for (c = 0; c < 75; c++)
{
/** Printing only those characters
whose count is at least 1 */
if (count[c] != 0)
printf("%c occurs %d times in the entered string.\n",c+'0',count[c]);
}
return 0;
}