行计数C ++ [英] Line counting C++

查看:178
本文介绍了行计数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个和平的计数程序中的逻辑线,省略注释和黑线。计数行正在工作,但我不知道如何省略注释行,我尝试

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 :/

总线和总注释行,我将减去 totalLines-commentLines 以了解真实的程序行数。

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.

有人可以帮我吗?

谢谢

#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;
}


推荐答案

考虑像下面这样的行:

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

非注释行。

实际上,tThis包含代码和注释,所以你可以

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. 一个包含看起来像注释的字符串



  2. 可以创建一个错误的注释分隔符
  3. li>
  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

可能更多的问题比那(虽然只是发生在我立即),但那些应该足以给至少一个一般的味道。

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.

底线:我想(至少),至少需要一个相当完整/准确的 C ++词法分析器。你可能不需要一个完整的解析器,但我认为没有使用完整的C + +词法的任何尝试几乎肯定会失败,可能是相当糟糕,很频繁。

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.

这篇关于行计数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆