سؤال

I have a text file which I have filled a number lines from different texts, having different line length.
What I want to do is calculate the average number characters per line which matters to me in my job. I wrote the following code in C to achieve this. However I cannot run the program once it is compiled.

#include<stdio.h>
#include<stdlib.h>

#define LENGTH 10000000

int main()
{
    char c;
    int i;
    int line_length;
    int j;
    int char_count;
    char char_a[LENGTH];
    int line_a[LENGTH];
    int line_count;
    long sum;
    float avg_char_count;
    FILE *fp=fopen("input.txt","r");
    if(!fp){
        fprintf(stderr,"cannot open file");
        exit(1);
    }
    /*read into file*/
    i=0;
    sum=0;
    while(char_a[i++]=fgetc(fp))
            sum++;

    printf("chars count: %d \n",sum);

    /*process array*/
    char_count=i;
    j=0;    
    line_count=0;
    while(j++<char_count){
        if(char_a[j]=='\n'){
            sum--;
            line_count++;
        }   
    }

    /* calculate the average*/
    avg_char_count=sum/(float)line_count;
    printf("\naverage # of chars in a line is: %f\n ",avg_char_count);
    return  EXIT_SUCCESS; 
}   

By the way I am using Borland C++ command-line tool BCC32, running on Windows 7 SP1.
What's wrong with my code?

هل كانت مفيدة؟

المحلول

Try declaring char_a and line_a as pointers to char and int as:

char *char_a;
int *line_a;

And then allocate memory dynamically using malloc.

char_a=(char*)malloc(10000000*sizeof(char));
line_a=(int*)malloc(10000000*sizeof(int));

Secondly, your while loop should end when you reach end of file, i.e. EOF.

while(char_a[i]=fgetc(fp)){
            if(char_a[i++]==EOF)
                break;

                sum++;
     }

And, you should initialize the line_count to 1 instead of 0, because when there is no '\n' in the text file, there can still be one line. If there is one '\n' in the text file, it means there are two lines (say, you are in line 1, and then you hit enter, which is '\n', and then you get to the new line, so for one '\n', there are 2 lines).

    /*process array*/
    char_count=sum;
    j=0;
    line_count=1;
    while(j++<char_count){
        if(char_a[j]=='\n'){
            sum--;
            line_count++;
        }
    }

NOTE-Currently your char_count include newlines ('\n') when it is printed. Print the statement in the end, because in the end of your program, you have already excluded the newlines by decrementing the sum in the if statement of the second while loop.

نصائح أخرى

The most probable cause is that you allocate 20 Mb of variables on the stack.

I would change the program so that it reads the file on line at a time (or even one character at a time). That way you only need to allocate space for one line and not for the entire file.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top