程序在c中从行读取并给出:文件中的数字和其他字符

时间:2015-12-31 03:12:17

标签: c

我应该制定以下计划: 我们想要编写一个程序.c以及它的algoritham,使用以下指示:   - 程序将计算传递给参数的文件的字符数,即在命令行上,这将在两个单独的类别中重新组合这些字符:

  • 数字[0-9];
  • 其他角色;

(文件是“非结束”,即不能放在表格的中央存储器中) 示例:

>cat kisses.txt
I am very happy to get 1 good answer, or 5!
>count kisses.txt
numbers: 2
others: 41

我试图做的事情:

#include<stdio.h> 
int main(int argc, char**argv){
FILE *fd ;

int nb=0, cpt=0;


if ((fd=fopen(argv[1], ‘r’) !=NULL){

unsigned int=c ;
while(c=fgetc(fd) !=EOF){
if (c>45 && c<= 57} 
nb++ ;
}
else {
cpt++
}
printf(‘numbers: %d\n and the other charaters are = %d, nb, cpt) ; 
fclose(fd);
return 0 ; 
}

(如果有人可以检查这段代码并为我的算法提供正确的伪代码,我将不胜感激)

1 个答案:

答案 0 :(得分:4)

仔细比较一下你自己试图了解你出错的地方......

int main ( int argc, char ** argv ) {

    FILE *       fp;     /* calling a FILE* "fd" will confuse people */
    int          nb = 0;
    int          cpt = 0;
    int          c;

    if (argc <= 1) return 1;       /* make sure there is a filename */
    if ((fp = fopen(argv[1], "r")) != NULL) {
        while ((c = fgetc(fp)) != EOF) {
            if ((c >= '0') && (c <= '9')) {   /* better than numbers */
                nb++;
            } else {
                cpt++;
            }
        }
    }
    printf("numbers: %d\n and the other charaters are = %d\n", nb, cpt) ; 
    fclose(fp);
    return 0; 
}

另外,不要害怕空白 - 它使事情更具可读性!