Line counting C++

梦想的初衷 提交于 2019-12-20 07:12:57

问题


I'm working with this peace of that count the logical lines in a program, omitting comments and black lines. The counting line is working, but I don't know how to omit the comment lines, I try

if (line == "//")
{
    comment++;
}

but it only checks for lines that start with "//" and if there's text next to that it doesn't count that as a comment line :/

At the end when I know the total lines and total comment lines, I will subtract totalLines-commentLines to know the real program number lines.

Can someone help me with this?

Thank you

#include <iostream>
#include <fstream>
#include <istream>
using namespace std;

int main()
{
    int numlines = 0;
    int comment = 0;
    string line;

    ifstream myfile("wr.cpp");
    while (myfile.good())
    {
        getline(myfile, line);
        if (line == "//")
        {
            comment++;
        }
        if (line == "/**/")
        {
            comment++;
        }
        ++numlines;
    }
    cout << "Number of lines: " << numlines << endl;
    cout << "Number of comment lines: " << comment << endl;
    return 0;
}

回答1:


I think your methodology is...flawed.

Consider a line like:

int x = 1;    // starting from 1 because [some reason]

As your code stands right now, it counts only as a non-comment line. As you've described what you'd like to do, it would count only as a comment line.

In reality, tThis contains both code and a comment, so you'd normally want to count it as both code and comment, not just one or the other.

Doing this job well is decidedly non-trivial. Obvious problems you encounter are:

  1. a string that contains something that looks like a comment
  2. line continuation
  3. trigraphs
    • Can hide line continuation
    • Can create a false comment delimiter
  4. Multi-line C-ctyle comments
  5. #ifs, #ifdefs, etc.

There are probably more issues than that (though are just what occurred to me immediately), but those should be enough to give at least a general flavor.

Bottom line: I think to get very far with this (at all) you're doing to at least need a reasonably complete/accurate C++ lexer. You probably don't need a full parser, but I think any attempt that doesn't use a full C++ lexer s almost certain to fail, probably quite badly and quite frequently.



来源:https://stackoverflow.com/questions/21357005/line-counting-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!