使用未声明的标识符'buffer'和未使用的变量'buffer'

Mic*_*ael -1 c++ compiler-errors

我在memcpy上使用未声明的标识符'buffer'(buffer,&m_Text [index],m_Index - index); 并返回atof(缓冲区); char缓冲区[32] = {0}上的未使用变量'缓冲区'错误; 有没有办法解决这个问题?非常感谢

double GetNumber()
{
    SkipWhitespaces();

    int index = m_Index;
    while (isdigit(m_Text[m_Index])) m_Index++;
    if (m_Text[m_Index] == '.') m_Index++;
    while (isdigit(m_Text[m_Index])) m_Index++;

    if (m_Index - index == 0)


    char buffer[32] = { 0 };
    memcpy(buffer, &m_Text[index], m_Index - index);

    return atof(buffer);
}
Run Code Online (Sandbox Code Playgroud)

use*_*301 5

让我们添加一些额外的括号来演示正在发生的事情

double GetNumber()
{
    SkipWhitespaces();

    int index = m_Index;
    while (isdigit(m_Text[m_Index])) 
    { // added brace
        m_Index++;
    } // added close brace.
    if (m_Text[m_Index] == '.') 
    { // added brace
        m_Index++;
    } // added close brace.
    while (isdigit(m_Text[m_Index]))
    { // added brace
        m_Index++;
    } // added close brace.

    if (m_Index - index == 0)
    { // added brace
        char buffer[32] = { 0 };
    } // added close brace.
    memcpy(buffer, &m_Text[index], m_Index - index);

    return atof(buffer);
}
Run Code Online (Sandbox Code Playgroud)

按照最初的if说法,声明没有正文,因此它将下一行作为正文.因为char buffer[32] = { 0 }; 它是下一行,所以它if一旦if退出就会成为一部分并且超出范围,当时不再存在memcpy尝试使用它.

我强烈建议在学习的同时始终包括所有大括号.它有助于防止错误.如果你愿意,你可以稍后省略它们,但我总是发现它们比障碍更有帮助.

查看来自源博客的原始代码,我发现

if(m_Index - index == 0) 
    throw ParserException("Number expected but not found!", m_Index);
Run Code Online (Sandbox Code Playgroud)

if (m_Index - index == 0)
 
Run Code Online (Sandbox Code Playgroud)

添加缺失的行(最好与省略的大括号一起添加)并char buffer[32] = { 0 };再次处于正确的范围内.