我有这段代码读取另一个文件并计算行数;那部分工作正常。
我要做的是省略注释行,因此程序只读取实际代码而不是注释。
希望有人可以帮助我:/
#include <iostream>
#include <fstream>
#include <istream>
using namespace std;
int main() {
int numlines = 0;
string line;
ifstream myfile("wr.cpp");
while (myfile.good ())
{
getline(myfile, line);
++numlines;
}
cout << "Number of lines: "<<numlines<< endl;
return 0;
}
答案 0 :(得分:2)
首先,while (myfile.good ())
是错误的。它应该是while (std::getline(myfile, line))
。测试good()
将仅测试您尝试阅读之后的流的状态(并且已经增加了您的计数)。测试getline
电话会立即对其进行测试。
之后,您只需检查前2个字符以查看它是否为注释行(假设//
和/*
是您的注释块,并且所有注释只是一行):
while (std::getline(myfile, line))
{
std::string test = line.substr(0, 2);
if (!(test == "//" || test == "/*"))
{
++numlines;
}
}