Home > database >  Program which prints a random number when it counts the number of words from a file in C
Program which prints a random number when it counts the number of words from a file in C

Time:05-29

I am trying to create a program which :

1. counts the number of the words

2. counts the length of the words from a file but

My problem is that I notice something that I did not expected the file has four words words but when it counts the length of words the program prints a random number 77

The file :

vasilis
giorgos
anastasia
nikos

code :

#include<stdlib.h>
#include<string.h>

int main ()
{
    FILE *fp ;

    fp=fopen("C:\\Users\\TOSHIBA\\Downloads\\sample.txt","r");

    if (fp==NULL)
    {
        printf("the file is empty");
    }
    //count the number of words
    int counter =1;
    char ch;
    while((ch=fgetc(fp)) != EOF)
    {
       if (ch=='\n')
       {
             counter;
       }
    }

    fseek(fp,0,SEEK_SET);

    //count the length of words

    int length[counter];
    char ch1;
    int counter1 = 0 , i=0;

    while( (ch1 = getc(fp))!= EOF )
    {
        if (ch1 == '\n')
        {
            length[i]=counter1;
            i  ;
            counter1=0;
            continue;
        }
        counter1  ;

    }

    // print the length of every word

    for (i = 0; i < counter; i  )
    {
        printf("\n%d",length[i]);

    }
    return 0;
}

CodePudding user response:

The program cannot read the number of charectars in the last word as there is no \n at the end of that word. The code should be modified like this- enter image description here

  • Related