我正在尝试遍历一个文本文件,扫描它并找到以 #| 开头的多条评论并以 |# 结尾并打印出来。我正在使用 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/