C++ 跳过C++;

C++ 跳过C++;,c++,counter,lines-of-code,C++,Counter,Lines Of Code,我有一个软件工程课的作业,这让我抓狂。我被要求设计一个行计数器,它只计算任何给定文件的逻辑代码行。它必须省略空行和注释 我的代码运行得很好,只是不管我传入什么文件,它都会将行号多计2行。我一辈子都看不出我的问题在哪里,我想知道是否有人能帮我解决 这是我的密码: #include <iostream> #include <fstream> #include <string> #include <cstring> #include <stdio.

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

我的代码运行得很好,只是不管我传入什么文件,它都会将行号多计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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
//初始化变量
河流充填;
字符串文件名;
内线=0;
//获取文件输入
cout文件名;
//打开文件
open(filename.c_str());
//阅读并跳过空行和注释
while(getline(填充,文件名)){
if(filename.empty()| | filename.find(“/”)==true){
继续;
}
//增加行号
++线路;
}
//关闭文件
infle.close();
//显示结果

cout为什么不添加一个打印语句,例如
cout替换
filename.find(“/”==true
文件名。find(“/”==0
查找以
/
开头的行,这样它就不会认为
int i=0;//comment
之类的行是非代码行

  • empty()的意思是“完全没有字符”,而您还希望筛选出只包含空格和制表符的行
  • 您可能在包含
    //
    的行中有代码(例如
    inti;//循环索引
    ),因此过滤掉它们将得到错误的结果
  • 做事情的一个可靠方法是:

  • 条状评论
  • 带空白
  • 然后查看剩余的行是否为空

    C/C++中的字符串处理是可怜的,因此您将是第1000.000个被迫编写(或复制)修剪字符串两端空格所需代码的可怜人


    顺便说一句,调用
    filename
    一个应该包含当前行的变量并不是香蕉林之外的捷径。

    您不需要执行
    infle.open(filename.c_str())
    。只需
    infle.open(filename)
    可以。@zenith:取决于标准库的版本。
    std::string
    重载是在应该添加的很久之后添加的。如果不知道如何使用函数,也不应该使用它们。
    string::find
    如果在字符串中找到,则返回参数的位置;如果在字符串中找不到,则返回
    npos
    找到,不是布尔值。@BenVoigt哦,好的,谢谢你提供的信息。你忽略了像
    ++i;//increment i
    这样的行。你正在计算只包含空格的行。这不起作用。我尝试了你的建议,我的输出从24行代码到30行代码,这意味着它在某些地方变得更加不准确。@n\u alvarez2007 i w并没有说这是您必须进行的唯一修改。这会为我返回大量错误。首先,ltrim和rtrim返回为无效,因为它们未在我的程序范围内声明。但我将此归因于未声明它们所属的库。@n_alvarez2007-我不会为您做功课。堆栈溢出不是你自己的机械土耳其人。
    ltrim
    rtrim
    功能你需要从我在答案底部给你的链接中复制。如果像这样比较查找结果会更好:filename.find(foo)!=字符串::npos@Y00-这将错误地排除既有代码又有语句的行。例如:
    area=PI*radius*radius;//计算圆的面积
    将被排除,即使它有有效的代码。
    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;
    }