c++ - 检查文本文件中的多条评论并打印出来

标签 c++ c++11 c++14 c++17

我正在尝试遍历一个文本文件,扫描它并找到以 #| 开头的多条评论并以 |# 结尾并打印出来。我正在使用 get 函数循环遍历每个字符,并使用 peek 函数检查下一个字符。目前我的代码无法识别结束注释。请帮忙。

我尝试遍历每个字符,将其与多条评论进行比较并将其存储在 vector 中

void Scanner::readingThroughTheFiles(ifstream& inFile)
{
    lineNumber = 0;
    inFile.open(fileName);
    while (!inFile.eof()) {
        char c = '\0';
        while (inFile.get(c)) { // loop getting single characters
            tokens = c;
            isAText(inFile);
            isAWord(inFile);
            // isAComment(inFile);
            if (c == '\n') {
                lineNumber++;
            }
            if (c == '#' && inFile.peek() == '|') {
                char next = inFile.peek();
                multipleComment += c;
                multipleComment += next;
                char c = tokens;
                while (inFile.get(c)) {
                    multipleComment += c;
                    if (tokens == '|' && next == '#') {
                        tokenTypes.push_back(multipleComment);
                        values.push_back("COMMENT");
                        // lineNumbers.push_back(lineNumber);
                        multipleComment.clear();
                    }
                }
            }

最佳答案

您的代码中的问题在这里:

if (tokens == '|' && next == '#') {

这个条件永远不可能为真,因为你只设置了一次next(上面的几行)并且它的值总是|。看到这一行:

char next = inFile.peek();

第二个问题是变量tokens 的值总是#。也许您想做类似的事情?

if (c == '|' && inFile.peek() == '#') {
    // rest of your code
}

编辑:如果您想保存行号,您还应该在第二个 while 循环中检查 \n。否则,如果您的评论跨越多行,您的行号将不会增加。

但是您应该在进入第二个 while 循环之前临时存储行号。如果您不这样做,则存储在 vector lineNumbers 中的行号将始终是最后的行号。

int lineNumberSave = lineNumber;
while (inFile.get(c)) {
    multipleComment += c;
    if (c == '|' && inFile.peek() == '#') {
        // rest of your code
        lineNumbers.push_back(lineNumberSave);
    }
}

关于c++ - 检查文本文件中的多条评论并打印出来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274886/

相关文章:

c++ - Qt - std::unordered_map - 销毁时间

c++ - 这个模板语法和无符号类型是什么?

c++ - 如何 static_assert 给定的函数调用表达式是否可以编译?

c++ - 如何在编译时提取没有路径和后缀的源文件名?

c++ - new 和 delete 在 C++14 中仍然有用吗?

c++ - SFINAE 检查 operator[] 比我还糊涂?

c++ - Qt 翻译 : What context should I use in the ts file for standard buttons like OK, 保存,取消?

C++ 流引用作为类成员

c++ - 使用平凡的复制构造函数传递类对象,但没有输出?

c++ - 在一种情况下 shared_ptr 导致运行时错误,在另一种情况下不会