【问题标题】:How can I pass an istream to a function in c++?如何将 istream 传递给 c++ 中的函数?
【发布时间】:2016-04-21 16:13:25
【问题描述】:

编辑:我在一次提交中更改了多个代码部分而没有意识到这一点,导致 cmets 中的大部分混乱。

现在我可以看到问题应该是什么了:如何将 istream 传递给 c++ 中的函数?

例子:

int ncharf()
{
    char neww;
    myfile.get(neww);
    return (int)neww;
}

myfile 是 istream

【问题讨论】:

    标签: c++ arguments


    【解决方案1】:

    您忘记将 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 有可能是一个全局变量,不需要传递。
    • @ThomasMatthews 查看 OP 收到的错误消息。它抱怨.get 没有应用于类对象。
    • 如果我想以二进制模式从文件中读取一个int,我需要在get方法中指定int的大小,否则它读取一个特点。例如:myfile.get((char *) &new, sizeof(int)).
    • get() 读取 char 和 c-strings 而不是 int,如果遇到分隔字符(默认为'\n')将停止读取。
    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 2011-01-09
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多