2017-02-22 30 views
-3

Я попытался выполнить программу, которая подсчитывает количество слов, строк и символов в TXT-файле. Когда я запускаю программу, она всегда показывает 0 для обеих строк и слов и дает мне неправильное число для количества символов. Если кто-то может выделить ошибки для меня, это было бы здорово. Заранее спасибо = DПодсчет слов, строк и символов из файла в C

#include <stdio.h> 
#include <ctype.h> 

int main(int argc, char *argv[]) 
{ 
    int x[1000]; 
    int w=0, l=0, c=0; //counters of words, lines and characters (respectively) 

    FILE *inp; 

    inp=fopen("text.txt", "r"); //opening the file 

    while(fscanf(inp, "%s", x)!=EOF) //checking if the end of the file 
    { 
     fscanf(inp, "%s", x); 
     c++; 
     if (fscanf(inp, "%s", x)==' '){ 
      w++; 
      c--; 
     } 
     else if (fscanf(inp, "%s", x)=='\n'){ 
      l++; 
      w++; 
     } 
    } 

    printf("The number of lines is: %d\n", l); 
    printf("The number of words is: %d\n", w); 
    printf("The number of characters is: %d\n", c); 

    fclose(inp); 

    return 0; 
} 
+0

Параметр ' '% s" 'в' fscanf (вх, „% s“, х) 'капли ведущих пробельных без сохранения их в' x'. Это означает, что количество символов не будет включать в себя бело- пробелы – chux

+0

Как вы можете читать слова и подсчитывать символы? Скажите, что вы читаете слова «foo», а затем «bar». Как вы можете узнать, сколько символов было? –

+0

'if (fscanf (inp,"% s ", x) == '') 'наиболее любопытно.' fscanf() 'возвращает количество проверенных элементов (или EOF). Зачем сравнивать этот счетчик элементов (который в этом случае будет 1 или меньше)?' Same для 'fscanf (inp,"% s ", x) == '\ n')'. – chux

ответ

1

Вы не можете сравнить fscanf(..,..,x) для считанных данных. Данные считывания находятся в x.

#include <stdio.h> 
#include <ctype.h> 

int main(int argc, char *argv[]) 
{ 
    int x[1000]; 
    int w=0, l=0, c=0; //counters of words, lines and characters (respectively) 

    FILE *inp; 

    inp=fopen("text.txt", "r"); //opening the file 

    int character_read; 
    while((character_read = fgetc(inp)) !=EOF) //checking if the end of the file 
    { 
     // One character was read 
     c++; 
     // Check if it is a separator char (count another word) 
     if ( character_read == ' ' 
      || character_read == '\n' 
      || character_read == '\t') 
     { 
      w++; 
     } 
     // Check if it was a newline (count a new line) 
     if (character_read == '\n') 
      l++; 


    } 

    printf("The number of lines is: %d\n", l); 
    printf("The number of words is: %d\n", w); 
    printf("The number of characters is: %d\n", c); 

    fclose(inp); 

    return 0; 
} 
Смежные вопросы