检查文本文件中的多注释并将其打印出来

Check for multi comment in a text file and print it out

本文关键字:打印 注释 文件 文本 检查      更新时间:2023-10-16

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

我尝试循环遍历每个字符,将其与多注释进行比较并将其存储在向量中

void Scanner::readingThroughTheFiles(ifstream& inFile)
{
    lineNumber = 0;
    inFile.open(fileName);
    while (!inFile.eof()) {
        char c = '';
        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循环之前暂时存储行号。如果您不这样做,存储在向量lineNumbers中的行号将始终是最后一个行号。

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