问题
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:
- a string that contains something that looks like a comment
- line continuation
- trigraphs
- Can hide line continuation
- Can create a false comment delimiter
- Multi-line C-ctyle comments
#if
s,#ifdef
s, 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