2013-06-18 37 views
-2

我寫了一個c代碼來計算文件中的字符數,位數和行數。不幸的是,行數沒有給出確切的計數。我寫下了下面的代碼。計算文件中的行數

#include<stdio.h> 

void scan(); 
FILE *fp; 

int numbercount=0,textcount=0,spacecount=0,newlinecount=0,specialcount=0; 

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

if(argc<2) 
{ 
    printf("\n Enter the filename through the command line ! "); 
} 
else 
{ 
    fp=fopen(argv[1],"r"); 
    if(fp==NULL) 
    printf("\n Cannot Open the file "); 
    else 
    scan(); 
} 
} 


void scan() 
{ 

char ch; 
while(1) 
{ 
    ch=fgetc(fp); 
    if((ch>=65 && ch<=90)||(ch>=97 && ch<=122)) 
    { 
     textcount++; 
    } 

    else if(ch>=48&&ch<=57) 
    { 
     numbercount++; 
    } 

    else if(ch==','||ch=='!'||ch=='?'||ch=='.') 
    { 
     specialcount++; 
    } 
    else if(ch==' ') 
    { 
     spacecount++; 

    } 
    else if(ch=='\n') 
    { 
     newlinecount++; 

    } 
    else if(ch==EOF) 
    break; 
} 

    printf("\n The count of charecters in the text = %d ",textcount); 
    printf("\n The count of numbers in the text = %d ",numbercount); 
    printf("\n The count of special charecters in the text = %d",specialcount); 
    printf("\n The count of newlines = %d ",newlinecount); 
    printf("\n The number of spaces = %d \n",spacecount); 

} 

我已經給輸入文本文件內容如下http://pastebin.com/GXVdqfzT,代碼給出了線數爲6,而不是11.是否有計算行數的適當方式。

+2

...文件似乎有一個6的行數,如pastebin中所示。我錯過了什麼嗎? – Bart

+1

換行和換行符有所不同。當空間用完時,請繼續打包。 – ChiefTwoPencils

+0

感謝您的輸入 –

回答

3

如果沒有。行數爲11,文本編輯器將顯示11作爲最後一行數字。它說6,這意味着由於字換行,字在下一行流動。複製粘貼到記事本沒有自動換行,你會看到。

行中沒有字符導致單詞被包裝到下一行(與存儲並導致換行的\n不同)。自動換行是編輯器的一項功能,它不依賴於數據(行中的字符)(它會檢查行是否超出編輯器窗口的當前寬度並進行換行)。

+0

我將禁用gedit中的換行選項。 –

2

該文件確實有6條線,他們都剛剛結束,並在原始數據與八進制或十六進制轉儲程序看起來像11

4

疑問時您輸入的樣子......一個也顯示可讀的Ascii。你可以看到實際的線條。

此外,打開二進制文本文件甚至有助於理清奇怪的行爲。

BUG ALERT:如果最後一行沒有行尾字符會發生什麼?它發生了。