-2

I'm doing a program that count the lines of a .cpp file, the number of classes, the number of comments, the number of functions, and the number of lines inside a class or a function.

One of my problems it's that I can't compare the char where I am and the next of it.

Here's my code:

while(readfile.good())
{
    string compare;

     while(!readfile.eof())
     { 
       std::getline(readfile, compare);
       number_of_lines++;

       if(readfile.peek() == 47 && /*here i need to compare next character*/)
        lines_of_comment++;
       if((offset = compare.find("/*clase*/", 0)) != string::npos)
       {
         lines_of_comment++;
         number_of_class++;
       }
       else if ((offset = compare.find("/*funcion*/",0)) != string::npos)
       {
         lines_of_comment++;
         number_of_functions++;
       }
       else if ((offset = compare.find("/*end*/",0)) != string::npos)
         lines_of_comment++;
    }
  }

How can I compare that next character?

And if you can give me some ideas for how can I count lines inside a function.

LogicStuff
  • 18,687
  • 6
  • 49
  • 70
  • 1
    To do the things you're describing correctly, you need to implement a rather complex language parser. This is no small task, but unless you're in a compiler theory type class, it's not likely your professor expects you to do that. Searching for the start and end of a class or function is definitely more complex than simply searching for some basic text though. – mah Feb 01 '16 at 21:55
  • You should read about [why `eof` is almost never what you want](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Feb 01 '16 at 22:14

1 Answers1

1

To answer this line:

if(readfile.peek() == 47 && /*here i need to compare next character*/)

Basically, you want to peek for two characters. You can take this code ((1) or (2)):

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("Hello");
    std::cout << (char) iss.get();
    std::cout << (char) iss.peek(); // can be get() if you use (2)

    // (1)
    iss.unget();

    // (2)
    //iss.seekg(-1, std::ios_base::cur);

    std::cout << (char) iss.peek() << std::endl;
    return 0;
}

The output will be:

HeH

However, I don't get why you need to peek. Don't you want to parse compare? e.g.:

if(compare.length() >= 2 && compare.substr(0, 2) == "//")

Also note that you should be using std::getline(readfile, compare) as the loop condition instead of !readfile.eof() as mentioned in the comments. The outer while should be an if.

LogicStuff
  • 18,687
  • 6
  • 49
  • 70