2015-05-04 20 views
0

請告訴我下面的代碼有什麼問題。執行後,將其表示以大小寫不敏感的方式計算字符在文件中出現的次數的錯誤

「的test.txt具有字母 'R' 的0實例」

`#include<stdio.h> 
#include<stdlib.h> 
#include<ctype.h> 
int main() 
{ 
    FILE *fp; 
    char ch,cmp; 
    char f[100]; 
    int count=0,tu1,tu2; 
    printf("Enter the file name\n"); 
    scanf("%s",f); 
    fp=fopen(f,"r"); 
    printf("Enter the character to be counted\n"); 
    scanf("%c",&ch); 
    tu1=toupper((int)ch); 
    while((cmp=fgetc(fp))!=EOF) 
    { 
    tu2=toupper((int)cmp); 
    if(tu1==tu2) 
    { 
     count++; 
    } 
    } 
    fclose(fp); 
    printf("\nFile \'%s\' has %d instances of letter \'%c\'",f,count,ch); 
    return 0; 
}` 
+2

您的意見是什麼?文件的內容是什麼?嘗試在'scanf('%c',&ch);'%c' –

回答

2

點1

使用前始終檢查的fopen()的研製成功返回文件指針。在此(下面)行代碼之後,爲fp添加NULL檢查。如果爲NULL,中止程序

fp=fopen(f,"r"); 

點2

變化

scanf("%c",&ch); 

scanf(" %c",&ch); // mind the ' ' before c 

,以避免存儲尾隨換行符(\n)以前的ENTER鍵按。

點3

作爲每fgetc()man page,返回類型爲int。將cmp的數據類型從char更改爲int

注:

  1. main()推薦的簽名是int main(void)
  2. 它始終是一個很好的實踐的研究,以initlize局部變量。
相關問題