Thread: counting whitespace characters

  1. #1
    Registered User
    Join Date
    Oct 2003

    counting whitespace characters

    Hey, I have spent about an hour trying to figure out what is wrong with this code. I have tried every variation of it that I can think of. I'm trying to count the whitespaces in a text file. This function is, of course, only part of the program. When the program runs, "count" gets printed as 0. Everything I've tried ends up with "count" being zero. I can't figure it out. Thanks for the help in advance.

    Here's the code:

    void countspace( FILE* inFile)
        char ch;
        int count = 0;
        while (fscanf (inFile, "%c", &ch) != EOF)
           if (isspace(ch))
        printf("\nThere are %d white space characters.", count);

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Waterloo, Texas
    Could be the way you're analyzing the ret val of scanf. Don't use the function much myself. I did notice some inconsitencies with the code though. The function doesn't return anything - how useful is that? You shouldn't really be printing from within the function either since if you ever do reuse it, you'll always get a printout - extra baggage so to speak. Finally, since the function operates on an already open file, it should go back to where it started whenever the function completes. Here's a more robust approach. This function will count any given character, thus eeking out as much reusability as possible (the primary aim of a software engineer of course).

    unsigned int count_char(FILE * inFile, char what)
     int ch;
     unsigned int count = 0;
     unsigned int bookmark = ftell(inFile); // save the current position 
        while ((ch = fgetc(inFile)) != EOF)
           if (ch == what)
     fseek(inFile, bookmark, SEEK_SET); // restore file-position
     return count;
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
        return std::pow
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Counting the characters from each word from a text file
    By flipguy_ph in forum C Programming
    Replies: 6
    Last Post: 04-27-2009, 05:56 PM
  3. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  4. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  5. Counting characters
    By tay_highfield in forum C Programming
    Replies: 3
    Last Post: 01-29-2003, 12:54 PM