正在跳过C++中以//开头的注释行
Skipping comment lines starting with // in C++
我的软件工程课有一项作业,让我抓狂。我被要求设计一个行计数器,它只计算任何给定文件的逻辑代码行。它必须省略空行和注释。
我的代码基本上是有效的,除了无论我把什么文件传给它,它都会把行号多算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
这样的行是非代码行。
- empty()的意思是"根本没有字符",同时您还希望过滤掉只包含空格和制表符的行
- 您可能在包含
//
(例如int i; // loop index
)的行中有代码,所以过滤掉它们会得到错误的结果
一个确定的做法是:
- 条形注释
- 条形空白
然后查看剩余的行是否为空。
C/C++中的字符串处理是可悲的,所以你将是第1.00000个可怜的家伙,被迫编写(或复制)必要的代码来修剪字符串两端的空格。
顺便说一句。将CCD_ 8称为一个应该保持当前行的变量并不是走出香蕉林的捷径。
相关文章:
- Visual Studio 2019:插入多个C++风格的单行注释
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 字符串开头的分隔符
- 设计将引用元素移动到开头的数据结构.C++
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 为什么 std::next 在以空地图开头馈送时卡住
- VSCode 中带有 C/C++ 扩展名的多行注释缩进错误
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- 如果我注释掉换行符,为什么'string'会成为一个不合格的变量
- 为什么 ## aka 令牌粘贴运算符不适用于 C 和 C++ 中的注释?
- 为什么使用 QString::right 在字符串开头省略逗号?
- c++ 如何在数组的开头添加值并为其编制索引?
- 如何在 的开头<x>和结尾<y>之间更改带有文件输出的字符串的值
- "Program ended with exit code: 0"出现在我的输出的开头?
- 在 // C++注释中使用 \\ 是否合法?(C++评论中的LaTeX方程)
- 如何找到循环列表的开头?
- 如何在C++中.txt文件的开头插入字符串
- 注释一行使代码工作,而没有它,代码不起作用
- 正在跳过C++中以//开头的注释行