正在跳过C++中以//开头的注释行

Skipping comment lines starting with // in C++

本文关键字:开头 注释 中以 C++      更新时间:2023-10-16

我的软件工程课有一项作业,让我抓狂。我被要求设计一个行计数器,它只计算任何给定文件的逻辑代码行。它必须省略空行和注释。

我的代码基本上是有效的,除了无论我把什么文件传给它,它都会把行号多算2行。我一辈子都看不出我的问题在哪里,想知道是否有人能帮我。

这是我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <stdio.h>
using namespace std;
int main () {
    // Initialize variables
    ifstream infile;
    string filename;
    int line = 0;
    // Get file input
    cout << "Enter the filename" << endl;
    cin >> filename;
    // open the file
    infile.open(filename.c_str());
    // read the lines and skip blank lines and comments
    while(getline(infile, filename)) {
        if(filename.empty() || filename.find("//") == true) {
            continue;
        }
        // increment the line number
        ++line;
    }
    // close the file
    infile.close();
    // display results
    cout << "There are " << line << " lines of code in this file." << endl;
}

终端中的计数器显示如下:"此文件中有24行代码。"

根据我的计算,应该只有22行逻辑代码。我们将不胜感激。

为什么不添加诸如cout << filename << 'n';之类的打印语句来标识它所标识的行?我怀疑你会看到一些空行。

我怀疑你需要去掉字符串中的空白。您可能有一些包含空格或制表符的空行。因此,就str::empty而言,它们在技术上并不为空。

此外,通过修剪和修复我在代码中看到的另一个错误,将"//"作为注释处理。

因此,它变成了一个简单的修剪修复。

while(getline(infile, filename)) {
    filename = ltrim(filename);  // remove leading whitespace
    filename = rtrim(filename);  // remove trailing whitespace
    if(filename.empty() || (filename.find("//") == 0)) {
        continue;
    }
    // increment the line number
    ++line;
}

你可以在这里的另一个SO答案上找到rtrim和ltrim的实现。

filename.find("//") == true替换为filename.find("//") == 0,以查找以//开头的行,这样就不会认为像int i = 0; // comment这样的行是非代码行。

  1. empty()的意思是"根本没有字符",同时您还希望过滤掉只包含空格和制表符的行
  2. 您可能在包含//(例如int i; // loop index)的行中有代码,所以过滤掉它们会得到错误的结果

一个确定的做法是:

  1. 条形注释
  2. 条形空白

然后查看剩余的行是否为空。

C/C++中的字符串处理是可悲的,所以你将是第1.00000个可怜的家伙,被迫编写(或复制)必要的代码来修剪字符串两端的空格。

顺便说一句。将CCD_ 8称为一个应该保持当前行的变量并不是走出香蕉林的捷径。