【发布时间】:2016-04-21 16:13:25
【问题描述】:
编辑:我在一次提交中更改了多个代码部分而没有意识到这一点,导致 cmets 中的大部分混乱。
现在我可以看到问题应该是什么了:如何将 istream 传递给 c++ 中的函数?
例子:
int ncharf()
{
char neww;
myfile.get(neww);
return (int)neww;
}
myfile 是 istream
【问题讨论】:
编辑:我在一次提交中更改了多个代码部分而没有意识到这一点,导致 cmets 中的大部分混乱。
现在我可以看到问题应该是什么了:如何将 istream 传递给 c++ 中的函数?
例子:
int ncharf()
{
char neww;
myfile.get(neww);
return (int)neww;
}
myfile 是 istream
【问题讨论】:
您忘记将 myfile 作为参数传递。
int ncharf(istream &myfile)
{
char neww;
myfile.get(neww);
return (int)neww;
}
另外,正如@Barmar 评论的那样:The argument to .get() must be of type char, not int。
如果你想从二进制文件中读取 int,你应该使用 istream::read 代替:
int ncharf(istream &myfile)
{
int neww;
myfile.read((char*)&neww, sizeof(int));
return neww;
}
【讨论】:
myfile 有可能是一个全局变量,不需要传递。
.get 没有应用于类对象。
get方法中指定int的大小,否则它读取一个特点。例如:myfile.get((char *) &new, sizeof(int)).
get() 读取 char 和 c-strings 而不是 int,如果遇到分隔字符(默认为'\n')将停止读取。