2015-09-12 29 views
-1

在線編輯器中執行此代碼,但總是得到File 'test.txt' has 0 instances of letter 'r'。該怎麼辦? File 'test.txt' has 99 instances of letter'r'。這是預期的輸出。程序計算一個字符出現在文件中的次數(不區分大小寫)

#include<stdio.h> 
#include<stdlib.h> 
#include<ctype.h> 
int main() 
{ 
    FILE *fptr; 
    int d=0; 
    char c; 
    char ch,ck; 
    char b[100]; 
    printf("Enter the file name\n"); 
    scanf("%19s",b); 
    fptr=fopen(b,"r"); 
    printf("Enter the character to be counted\n"); 
    scanf(" %c",&c); 
    c=toupper(c); 
    if(fptr==NULL) 
    { 
     exit(-1); 
    } 
    while((ck=fgetc(fptr))!=EOF) 
    { 
     ch=toupper(ck); 
     if(c==ch||c==ck) 
      ++d; 
    } 
    fclose(fptr); 
    printf("File '%s' has %d instances of letter '%c'.",b,d,c); 
    return(0); 
} 
+1

'龜etc()''返回int',所以'ck'也應該是一個'int'。 – alk

+0

爲什麼'19'在這裏'scanf(「%19s」,b);'當'b'最多可以保存99個字符時,NUL終止符爲+1?順便說一句,發佈'test.txt'的內容。 –

+1

除了'ck'的問題,代碼看起來不錯。 – alk

回答

0

問題:

  1. ck應該是一個int,而不是作爲char@alkhas pointed out因爲fgetc返回一個int,而不是char
  2. 根據標題,你想要一個不區分大小寫的比較。你的代碼不會那樣做。該解決方案是這樣的:

    ​​

    需要是

    if(c == ch || (tolower(c)) == ck) /* Compare upper with upper, lower with lower */ 
    
+0

這是** C ** ,而不是** C++ **。使用'tolower(c)'而不是'c.tolower()'。 –

+0

@ Xis88謝謝指出! –

0

我測試了它。它工作正常。如果沒有提供失敗的測試文件,我無法檢測到您的問題。就我而言,它完成它應該做的事 - 它計算指定字符在指定文件中出現的次數(不區分大小寫)。這是你的代碼的美化版本。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> /* strlen */ 
#include <ctype.h> 

#define MAX_FILENAME_LENGTH 100 

int main(int argc, char **argv) { 
    /* Variables */ 
    FILE *file = NULL; 
    int count = 0, file_char; 
    char target_char, filename[MAX_FILENAME_LENGTH]; 
    /* Getting filename */ 
    printf("Enter the file name: "); 
    fgets(filename, MAX_FILENAME_LENGTH, stdin); 
    /* Removing newline at the end of input */ 
    size_t filename_len = strlen(filename); 
    if(filename_len > 0 && filename[filename_len - 1] == '\n') { 
     filename[filename_len - 1] = '\0'; } 
    /* Opening file */ 
    file = fopen(filename, "r"); 
    if(file == NULL) exit(EXIT_FAILURE); 
    /* Getting character to count */ 
    printf("Enter the character to be counted: "); 
    scanf(" %c", &target_char); 
    target_char = toupper(target_char); 
    /* Counting characters */ 
    while((file_char = fgetc(file)) != EOF) { 
     file_char = toupper(file_char); 
     if(target_char == file_char) ++count; } 
    /* Reporting finds */ 
    printf("File '%s' has %d instances of letter '%c'.", 
      filename, count, target_char); 
    /* Exiting */ 
    fclose(file); 
    return EXIT_SUCCESS; } 
+0

謝謝大家..代碼現在正在工作..問題是文件'test.txt'滿足null條件。我檢查它是否適用於其他文件 –

相關問題