1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C program to mimic wc command in UNIX

  1. Aug 18, 2006 #1
    I did it the following way. The number of characters and lines are coming out fine, but the words are usually more than the actual given by wc.

    #include<stdio.h>
    int main()
    {
    FILE *fp;
    int words=0,chars=0,lines=0;
    char prev,curr; //prev variable is included to exclude multiple spaces.
    fp=fopen("input.txt","r");
    while((fscanf(fp,"%c",&curr))!=EOF)
    {
    chars++;
    if (curr=='\n') lines++;
    if ((curr==' ' && prev!=' ') || (curr=='\n' && prev!='\n')) words++; //prev variable comes into play here. if the current char is a space and the previous was also a space then it should not be counted.
    prev=curr;
    }
    printf("%d %d %d\n",chars,lines,words);
    return 0;
    }
     
    Last edited: Aug 18, 2006
  2. jcsd
  3. Aug 20, 2006 #2

    Eus

    User Avatar

    Use isspace() declared in ctype.h

    HiHo!

    The mistake is that you have not included the other whitespace characters
    (e.g., '\t' and '\r') as tokens that delimit a word.
    So, instead of (curr==' ' && prev!=' ') || (curr=='\n' && prev!='\n'), you
    should use those is*-functions (e.g. isspace()) declared in ctype.h.

    Regards,
    Eus
     
  4. Aug 20, 2006 #3

    Eus

    User Avatar

    Flawed algorithm

    HiHo!

    Oh, one more thing, you have not considered a test case like this one below.
    people<SPACE><ENTER>people.
    wc will count that as two words but yours will count that as three words.

    Regards,
    Eus
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: C program to mimic wc command in UNIX
Loading...