c++ - 调用函数时从 'char' 到 'char*' 的无效转换(c++)
问题描述
每次我loadChar(charVariable,positonOfCharacter)
用这段代码写:
bool LoadEntity::loadChar(char * outputChar,int position)
{
ifstream file(nameOfFile.c_str());
if(!(file.good()))
return false;
file.seekg(position);
if(file.get())
{
* outputChar = file.get();
return true;
}
else
return false;
}`
我收到此错误:invalid conversion from 'char' to 'char*
如果函数正确运行,代码应该返回 bool 并将 char outputChar 的值更改为 int 位置上的文件中的字符。是什么导致了这个问题?
解决方案
问题:
char charVariable;
...
loadChar(charVariable, positonOfCharacter);
在这里,您尝试传递一个值而不是函数预期char
的指针(即)。char*
这是非法的。
简单的解决方案:
调用函数时使用变量的地址:
loadChar(&charVariable, positonOfCharacter); // note the &
选择:
如果您对指针不太熟悉,您还可以更改函数的签名并使用引用而不是指针。引用允许您更改原始变量的值:
bool LoadEntity::loadChar(char& outputChar, int position) // note the &
{
...
outputChar = file.get(); // note: no * anymore
...
}
无关问题:
你的使用有问题get()
。以下将导致您读取两次文件但忽略第一个输入:
if(file.get())
{
* outputChar = file.get();
...
}
此外,如果没有可用的 char,则 if 仍可能被执行并返回 ture,因为无法保证该函数将返回 0。
更喜欢 :
if(file.get(*outputChar))
{
return true;
}
不用担心:如果无法从文件中读取任何字符,则不会更改输出字符。
推荐阅读
- python - 从另一个数据框的列组成数据框
- java - 无需额外分配即可将 CharSequence 转换为 String
- c# - FileProvider 尝试在具有外部路径的空字符串上调用 XmlResourceParser
- graphileon - Graphileon CORS 问题
- apache-kafka - 如何配置 Kafka 以重复未提交的偏移量消息?
- python - Sklearn PCA解释方差和解释方差比差
- jquery - 打开单个下拉菜单。简化代码
- reactjs - 将组件 defaultProps 设置为 null 是不好的做法吗?
- php - 为什么方法注入不适用于某些控制器方法?
- tsql - 如何用连字符和逗号分隔 concat 函数内的列?