如何读取 .cpp 文件中的下一个字符

How to read next char in .cpp file

我正在做一个程序来计算.cpp文件的行数,classes的数量,注释的数量,函数的数量,以及里面的行数一个 class 或一个函数。

我的一个问题是我无法比较我所在的字符和下一个字符。

这是我的代码:

while(readfile.good())
{
    string compare;

     while(!readfile.eof())
     { 
       std::getline(readfile, compare);
       number_of_lines++;

       if(readfile.peek() == 47 && /*here i need to compare next character*/)
        lines_of_comment++;
       if((offset = compare.find("/*clase*/", 0)) != string::npos)
       {
         lines_of_comment++;
         number_of_class++;
       }
       else if ((offset = compare.find("/*funcion*/",0)) != string::npos)
       {
         lines_of_comment++;
         number_of_functions++;
       }
       else if ((offset = compare.find("/*end*/",0)) != string::npos)
         lines_of_comment++;
    }
  }

如何比较下一个字符?

如果你能给我一些关于如何计算函数内行数的想法。

回答这一行:

if(readfile.peek() == 47 && /*here i need to compare next character*/)

基本上,您想查看两个字符。你可以拿这个代码((1)或(2)):

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("Hello");
    std::cout << (char) iss.get();
    std::cout << (char) iss.peek(); // can be get() if you use (2)

    // (1)
    iss.unget();

    // (2)
    //iss.seekg(-1, std::ios_base::cur);

    std::cout << (char) iss.peek() << std::endl;
    return 0;
}

输出将是:

HeH

但是,我不明白你为什么要偷看。你不想解析compare吗?例如:

if(compare.length() >= 2 && compare.substr(0, 2) == "//")

另请注意,您应该使用 std::getline(readfile, compare) 作为循环条件,而不是评论中提到的 !readfile.eof()。外面的 while 应该是 if.