C ++省略或添​​加额外的字符

时间:2014-05-18 23:01:37

标签: c++ string

所以我有一个有趣的错误。我有这段代码(这是部分代码):

 if (isQuote(ch))
                {
                    //Add it to the Buffer
                    strBuffer += ch;

                    do
                    {
                        //get Next Character from ifstream and add it to the strBuffer
                        getNextAndAdd(ch);


                        // check whether it is a \\'
                        if (isBackslash(ch) && (this -> peek() == '"'))
                        {
                            //if it is a backslash, activate check checkQuote
                            checkQuote = true;
                        }
                        //if it is another quote, dectivate check Quote otherwise, break the system
                        if (isQuote(ch))
                        {
                             if (checkQuote)
                             {
                                 checkQuote = false;
                             }
                             else
                             {
                                 break;
                             }
                        }
                        //IF EOF, do NOT continue repeating the last character
                        if (input -> eof()){break;}

                    }
                    while (isPrintable(ch)); // check that it falls within the SXL acceptance range
                    if (ch == '"')
                    {
                        //IF EOF, do NOT continue repeating the last character
                        if (input -> eof()){break;}

                        //output Buffer for TEST purposes
                        cout << strBuffer << endl;

                        //create new token and push it into the vector
                        tk = new Token (tkstring, strBuffer, row, col);
                        tokensUsed.push_back(tk);
                        startNewString();
                    }
                    tokenMatch = true;
                }

getNextAndAdd(ch)翻译为

void getNextAndAdd(char ch)
    {
       ch = nextChar();
       strBuffer += ch;
    }

我正在给它一些测试数据。我有一个文本文件,我输入测试数据。问题在于,如果我写例如"abc" "def",它们之间只有一个空格,它会将其读作"abc" 123,后者是一个数字,完全不同如果我做两个空格意味着"abc" "def" 那么它会把它读成2个字符串。我还检查了它是否是WHITESPACE,但后一种情况有2个SPACES已经识别出最后一个空格实际上是一个空格

任何想法为什么?我尝试删除字符串的最后一个字母,说可能是那个错误,但结果是"hello

由于

2 个答案:

答案 0 :(得分:1)

void getNextAndAdd(char ch)
{
   ch = nextChar();
   strBuffer += ch;
}

您可能会认为这会返回您刚刚在ch中阅读的字符。你错了。

结果,执行此代码后:

if (isQuote(ch))
{
    //Add it to the Buffer
    strBuffer += ch;

    do
    {
        //get Next Character from ifstream and add it to the strBuffer
        getNextAndAdd(ch);

ch 包含引号,并且两个引号将附加到strBuffer

答案 1 :(得分:0)

我通过更改2行代码来修复它。

第一个更改位于isQuote下,我删除了strBuffer += ch,而是在do {}循环下添加了addAndGetNext(ch)

在最后一个循环语句下添加了另一个addAndGetNext(ch)