检查文本文件中的多注释并将其打印出来
Check for multi comment in a text file and print it out
我正在尝试遍历一个文本文件,扫描它并找到以#|开头并以|#结尾的多个注释并将其打印出来。我正在使用 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);
}
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- Visual Studio 2019:插入多个C++风格的单行注释
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 检查文本文件中的多注释并将其打印出来
- 在C++中打印到标准输出时 /* 注释的行为