c++从文件中加载总是重复最后一个字符
C++ load from file keeps repeating last character
所以我在做一个编译器,我有这个LEXER的一部分,它检查一些字符是否形成一个整数或一个实数满足这个EBNF //REAL: DIGIT {DIGIT} . DIGIT {DIGIT} [ (e|E) [(+ | -)] <DIGIT> {DIGIT}
我有这部分代码(它的片段),它检查虽然不是EOF或令牌不匹配,但它继续对令牌进行分类
while (!isEOF() && !tokenMatch)
{
//Checking for INTEGERS and REAL
//INTEGERS: DIGIT {DIGIT}
if (isDigit(ch))
{
strBuffer += ch;
do
{
ch = nextChar();
strBuffer += ch;
}
while (isDigit(ch));
//REAL or ERROR
//REAL: DIGIT {DIGIT} . DIGIT {DIGIT} [ (e|E) [(+ | -)] <DIGIT> {DIGIT}
if (ch == '.')
{
do
{
ch = nextChar();
strBuffer += ch;
}
while (isDigit(ch));
//EXPONENT
if (ch == 'E' || ch == 'e')
{
char peek = input -> peek();
//CHECK FOR + | -
if(peek == '+' || peek == '-')
{
ch = nextChar();
strBuffer += ch;
ch = nextChar();
if (isDigit(ch))
{
do
{
strBuffer +=ch;
ch = nextChar();
cout << strBuffer << endl;
}
while (isDigit(ch));
}
问题在于当我必须加载文本文件并从中获取字符时。例如,如果我写123.12
WITH a Space, Lexer将在空白处停止。如果在EOF处没有空格,最后一个do while循环将永远重复。
Next Char的实现*input是一个流声明为:
ifstream* input = new ifstream("test.txt");
char nextChar()
{
*input >> noskipws >> ch;
//check for new line. If true, increment Row and start column from 1
if(ch == 'n')
{
row ++;
col = 1;
}
else if (ch == 't')
{
col +=4;
}
else
{
col++;
}
return ch;
}
你知道我该怎么解决这个问题吗?
谢谢
我要把nextChar
改成:
int nextChar()
{
int ch = input->getc();
if ( ch == EOF )
{
return ch;
}
//check for new line. If true, increment Row and start column from 1
else if(ch == 'n')
{
row ++;
col = 1;
}
else if (ch == 't')
{
col +=4;
}
else
{
col++;
}
return ch;
}
并确保在调用getChar
的地方使用int
类型的变量,并在继续之前将返回的值与EOF
进行比较。
相关文章:
- 使用连续分隔符和空最后一个字符进行拆分
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 比较最后一个字符,不区分大小写(带谓词?
- 在弦乐器中删除最后一个字符
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 在C 字符串中,为什么在最后一个字符之后,通过索引和()访问索引时行为是不同的
- 如何查看复杂度为 O(1) 的字符串流对象中的最后一个字符
- 最后一个字符行编辑
- 如何在C 中获得字符串的最后一个字符
- 如何在C++中删除 UTF-8 字符串的最后一个字符
- 如何获取输入文件的行的第二个和最后一个字符,并在C++中组成数组
- 输出流中的第一个字符将替换为该流中被删除的最后一个字符.为什么会这样
- 正在将最后一个字符发送到std::cout
- 获取字符串流中的最后一个字符,而不复制其整个缓冲区
- remove_if字符串中的最后一个字符
- 如何删除最后一个字符
- 从字符数组中删除第一个和最后一个'X'字符
- C++文件中的最后一个字符
- (C++)如何从特定(结束)点查找 std::string 中的最后一个字符
- 如何获取您放入 ostream 对象中的最后一个字符