c++ - Use of undeclared identifier 'buffer' and Unused variable 'buffer'
问题描述
im getting a Use of undeclared identifier 'buffer' on memcpy(buffer, &m_Text[index], m_Index - index); and return atof(buffer); and the Unused variable 'buffer' error on char buffer[32] = { 0 }; is there a way of fixing this ? many thanks
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 };
将再次处于正确的范围内。
推荐阅读
- python - Hessian 在 Python 中使用有限差分方法
- excel - 运行时错误 1004。对象工作表的方法范围失败
- python - 使用导入 keras 时无法导入名称“tf_utils”
- c - 如何从 c 头文件中提取函数原型以实现自动完成功能
- sql-server - 显示 SQL 语句 NULL 的动态 SQL
- python - 错误消息:尝试制作双重理解列表时“int object is not callable”
- mysql - 如何使用连接从表中搜索?
- dependencies - BitBake:我们可以在包名中使用 DEPENDS 吗?
- python - Django TemplateSyntaxError: 'endblock',预期为 'empty' 或 'endfor'。您是否忘记注册或加载此标签?
- html - 如何保持元素与可用空间对齐并以正确的空间垂直排列