【问题标题】:Finding numbered functions within C++ code?在 C++ 代码中查找编号函数?
【发布时间】:2019-06-21 15:11:16
【问题描述】:

只需要您的专家建议。

我有数百个 *.cpp 源代码文件,其中包括各种测试函数,语法如下:

void test1()
...
void test25()

一个 cpp 文件可能只有一个测试,void test1(),它可能有很多测试,例如 void test266() 或任何数字。

我喜欢计算所有这些函数,分别我想找到最大值的测试函数。号码在 函数名。 这可能是最后一个,但不一定是最后一个,例如

void test1()
[
...
}
void test3()
[
...
}
void test2()
[
...
}

也可能发生。

知道如何快速收集这些信息吗? 我对 C++ (VC 2013) 有点熟悉,但对我可能必须使用的 (C++) 正则表达式不太熟悉。

没有正则表达式:逐行读取 cpp 文件并搜索模式 testnumber ,计算它们然后执行该程序 通过批处理对我将管理的文件夹中的所有 *.cpp 文件进行处理,但是有没有一种工具可以更轻松地完成这项工作?

感谢任何提示。

【问题讨论】:

  • grepsort?类似grep -r . -e "void test" | sort
  • perl -nE 'BEGIN { $n = 0 } if (/\btest(\d+)\b/ && $1 > $n) { $n = $1 } END { say $n }'?
  • 或者,由于您是 Windows 用户,我会推荐 notepad++ 。它有一些简单的“在文件中查找”,您应该可以输入“void test*()”的模式
  • 这不是一个合适的单元测试框架和测试运行器应该管理的吗?
  • @ThomasSablik:那会打印test42 之后 test1792,不是吗?

标签: c++ regex search


【解决方案1】:

我个人会在 python 或 bash 之类的东西中执行此操作,但也可以使用 regex 库在 C++ 中完成:

#include <iostream>
#include <fstream>
#include <regex>
int main()
{
    //set up regex
    std::regex reg("void [a-zA-Z]*(\\w*)");
    std::smatch matches;
    //set up file
    std::ifstream infile("path/to/Cpp/file");
    //do the actual stuff
    std::string line;
    int max = 0;
    while (std::getline(infile, line))
    {
        if (std::regex_search(line, matches, reg))
        {
            int match = std::stoi(matches[1].str());
            if (match >= max)
                max = match;
        }
    }
    std::cout << max << std::endl;
    return 0;
}

【讨论】:

  • 非常感谢这个解决方案,它引导我走向正确的道路!
猜你喜欢
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 2013-03-13
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
相关资源
最近更新 更多