计算C中的2位数字

时间:2014-12-14 11:53:51

标签: c

我的程序有点问题,我必须计算文本文件中2位数的数量。文本文件由符号(本例中为字母)和数字组成。这是我到目前为止所得到的。

int main ()  
{  
FILE *fr;    
int digit;  
char num[256];     
 fr = fopen ("tekst.txt","r");  
   if(fr==NULL)
 printf("File cannot open");   
 return 0;  

 while (!feof(fr));   
 {   
  fscanf(fr,"%s",num);  
  printf("%s\n", num);  
}

/*9   
if(num==0)   
               digit=2;   
       else    
       for(digit=0;num!=0;num/=10,digit++);   
               printf("the amount of 2 digit numbers is:%d\n",digit);   
   */             
    fclose(fr);   


    system("PAUSE");   
    return 0;   
}   

有人能帮助我吗?

2 个答案:

答案 0 :(得分:3)

你是来自python吗?

if(fr==NULL)
 printf("File cannot open");   
 return 0;  

转换为

if(fr==NULL)
   printf("File cannot open");   
return 0;  

或者更确切地说

if(fr==NULL)
{
   printf("File cannot open");   
}
return 0;  

所以return 0之后的所有内容显然都没有执行,即使frNULL也是如此。

答案 1 :(得分:0)

这将计算文件中的两位数字。它将计为“(37)”或“37”而不是“07” 要包含前导零变化&& iTens >= '1' && iTens <= '9'&& iTens >= '0' && iTens <= '9'的数字。

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    FILE *pf = NULL;
    int iNumber = 0;
    int iCount = 0;
    int iHundreds = -1;
    int iTens = -1;
    int iOnes = -1;
    int iEach = 0;

    if ( ( pf = fopen ( "tekst.txt", "r")) == NULL) {
        perror ( "could not open file\n");
        return 1;
    }
    while ( ( iEach = fgetc ( pf)) != EOF) { // read a character until end of file
        if ( iEach >= '0' && iEach <= '9') { //number
            iHundreds = iTens; // for each digit read, move digits up the chain
            iTens = iOnes;
            iOnes = iEach;
        }
        else { // non number
            if ( iHundreds == -1 // if iHundreds is not -1, more than two digits have been read
            &&  iTens >= '1' && iTens <= '9'// check that iTens and iOnes are in range
            && iOnes >= '0' && iOnes <= '9') {
                iTens -= '0'; // convert character code to number, '3' to 3
                iOnes -= '0';
                iNumber = ( iTens * 10) + iOnes;
                iCount++;
                printf ( "%d\n", iNumber);
            }
            iHundreds = -1;
            iTens = -1;
            iOnes = -1;
        }
    }
    printf ( "Counted %d two digit numbers\n", iCount);
    return 0;
}