【发布时间】:2017-11-04 18:37:42
【问题描述】:
对于我的 C 类,我必须编写一个程序来计算文件中每个数字 (0-9) 的频率。我已经用 Java 编写了代码,但无法将其翻译成 C。任何帮助将不胜感激。我将在下面添加到目前为止的内容。文本文件的一部分被添加到代码的末尾以显示它的样子,一个随机的符号和数字字符串。
#include<stdio.h>
#define m 100
#define n 60
void main() {
char file_name[m]; FILE *input_file;
char symb, symb0, symb1, symb2, symb3, symb4, symb5, symb6;
char symb7, symb8, symb9;
int i;
printf("Enter name of the input file: "); scanf("%s", file_name);
input_file = fopen(file_name, "r");
while (input_file == NULL) {
printf("Error: There is no file \"%s\"\n", file_name);
printf("Enter file name (or \".\" to exit): "); scanf("%s", file_name);
if (strcmp(file_name, ".") == 0) return;
input_file = fopen(file_name, "r");}
//read each char of the file till the end
while ((symb=getc(input_file))!=EOF){
// if the char is between '0'-'9' print it
if(symb >= '0' && symb <='9'){
//printf("%c", symb);
switch(symb){
case '0' :
symb0++;
break;
case '1' :
symb1++;
break;
case '2' :
symb2++;
break;
case '3' :
symb3++;
break;
case '4' :
symb4++;
break;
case '5' :
symb5++;
break;
case '6' :
symb6++;
break;
case '7' :
symb7++;
break;
case '8' :
symb8++;
break;
case '9' :
symb9++;
break;
}
printf("%c", symb3);
}
}
printf("\n-= Count the Thisles in =-");
fclose(input_file);
}
//...1..1.'`.1.........2..2..2...../\......./%%%%\/%%\.3...4..
//......'............../\........./%%\../\./%%%%%%/\%%\33..4..
//...'.../\.........../%%\.../\.../%%\./%%\%/\%/\/%%\%/\......
//.'..../%%\./\......./%%\../%%\./%%%%\/%%\/%%\%%\%%%/%%\.55..
【问题讨论】:
-
一个由十个元素组成的数组怎么样,每个数字一个。将每个元素初始化为零,找到数字时增加。请记住,例如
'2' - '0' == 2. -
1) 你知道
symb1到symb9的初始值是什么吗?它们是未定义的 2)您正在增加 char 变量,这可能不是您的想法 -
一点也不差...差不多。将
symb声明为int以便能够检查EOF。其他符号也必须是整数并初始化symb0= 0到symb9= 0。那么应该可以工作了。 -
symb3是一个 int(或至少用作 int),使用:printf("%d", symb3); -
次要:
void main()==>int main(void)