Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Counter code

  1. Jun 17, 2005 #1
    Hi everyone,

    I need to write a C code program to count the # of fuctions used in a certain file (function counter)

    Can you guys give me some hints/suggestions/ideas ?

    Thanks,
    Stan
     
  2. jcsd
  3. Jun 17, 2005 #2

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Do you know how to read in a file one token at a time? You should be able to read each { and } symbol as an independent token. If you keep a running count of the braces, adding one for each { and subtracting one for each }, the number of functions in the file is the number of times the counter goes from zero to one.

    Of course, this is primitive -- in the real world, I would probably use regular expressions to match each line of the .cpp file.

    - Warren
     
  4. Jun 18, 2005 #3
    Thanks, Warren for the response.
    Can you please show me how to read in a file one token at a time...
     
  5. Jun 18, 2005 #4

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Stanley,

    Something like this:

    PHP:

    #include <iostream>

    int main( int argc, char** argv )
    {
        char str[100];
       
        // don't read more than 100 characters
        // and overflow the buffer
        cin.width(100);

        while( !cin.eof() )
        {
            cin >> str;
            ...
        }

        return 0;
    }
     
     
  6. Jun 18, 2005 #5

    Hurkyl

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    You could use the string class, instead of a char*, so you don't have to have an upper bound on the size of a read.

    But that doesn't read it in one token at a time, does it? Isn't, for example wouldn't,

    {return(0);}

    be something like 7 tokens? But they'd all be read in at once.


    Wouldn't it be conceptually easier to process the file one character at a time?
     
  7. Jun 18, 2005 #6

    chroot

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Yeah, true, Hurkyl, I don't know how the istream class treats punctuation. You're probably right, it doesn't treat (){}* etc. as delimiters.

    You're right, reading one character at a time might be easier.

    - Warren
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook