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

标签 c++ compiler-errors

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

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);
}

最佳答案

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

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);
}
如最初所写,if语句没有主体,因此将下一行作为主体。由于char buffer[32] = { 0 };是下一行,因此它成为if的一部分,并且在if退出时就超出范围,在memcpy尝试使用它时不再存在。
我强烈建议在学习时始终包括所有牙套。它有助于防止错误。如果需要,您可以稍后省略它们,但是我一直发现它们比障碍更有用。

查看源博客中的原始代码,我发现
if(m_Index - index == 0) 
    throw ParserException("Number expected but not found!", m_Index);
if (m_Index - index == 0)
 
添加缺少的行(最好与省略的花括号一起添加),并且char buffer[32] = { 0 };将再次位于正确的范围内。

关于c++ - 使用未声明的标识符 'buffer'和未使用的变量 'buffer',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50165660/

相关文章:

compiler-errors - gfortran如何处理无法访问的代码?

C++ 正则表达式 header 未注册 Netezza UDF

c# - 添加动态评级控件时出现奇怪的编译问题

c# - C#程序可以以 '{'开头吗?如果没有,为什么不呢?

c++ - Stroustrup 的 C++ : exercise 6. 2.3 字符类型转换对我不起作用

c++ - 无法在 C++ 中传递二维数组,这会导致错误无法将 int(*) 转换为 int*

c++ - Linux c++错误: undefined reference to 'dlopen'

c++ - 如何从 MFC 中的线程更改状态栏的 Pane 文本?

android - C++ 方法返回任何数据类型。

c++ - 命名空间 'forward' 中没有名为 'std' 的成员