簡體   English   中英

計算C中的2位數字

[英]Counting the amount 2 digit numbers in 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;   
}   

有人可以幫我嗎?

您來自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;  

因此,即使fr是否為NULLreturn 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM