• Support PF! Buy your school textbooks, materials and every day products via PF Here!

Counter code

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
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,166
34
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
 
Thanks, Warren for the response.
Can you please show me how to read in a file one token at a time...
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,166
34
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;
}
 

Hurkyl

Staff Emeritus
Science Advisor
Gold Member
14,847
15
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?
 

chroot

Staff Emeritus
Science Advisor
Gold Member
10,166
34
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
 

Physics Forums Values

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top