【问题标题】:how to use ifstream as a function parameter?如何使用 ifstream 作为函数参数?
【发布时间】:2019-11-25 00:35:54
【问题描述】:

当我创建以下函数时,

int readDataFromFile(ifstream&  openFileStream, Snowman data[ ]){
    double height;
    double weight;
    double temp;
    bool hat;
    string scarf;
    int count = 0;
    while(openFileStream >> height) {
        openFileStream >> weight;
        openFileStream >> temp;
        openFileStream >> hat;
        openFileStream >> scarf;
    }
    return count;
}

这些部分是假的;

openFileStream >> height;
openFileStream >> weight;
openFileStream >> temp;
openFileStream >> hat;
openFileStream >> scarf;

结果:

二进制表达式的无效操作数('std::__1::ifstream'(又名'basic_ifstream')和'double')

我会在main()函数中打开ifstream,但是如何将它传递给另一个函数呢?

【问题讨论】:

  • 这与将std::ifstream 传递给函数无关。很可能您忘记了#include 所需的头文件,但没有人能够肯定地告诉您这一点,因为显示的代码无法满足minimal reproducible example 的要求,如help center 中所述。有关更多信息,请参阅How to Ask。如果您需要进一步的帮助,请edit 您的问题,直到符合minimal reproducible example 的所有要求。
  • 检查您是否使用了文件顶部的#include<fstream> 和显示的代码,并形成一个完整的minimal reproducible example 来编辑您的问题,否则只有猜测。
  • 看看我下面的回答。它应该给你一个线索,你可能会出错

标签: c++ compiler-errors parameter-passing ifstream


【解决方案1】:

看看下面的我的 sn-p,它适用于 Windows。注意ans.txt 只包含 2 个双精度值

#include <fstream>    
#include <iostream>

void printcontents(std::ifstream& inp)
    {
        double val1, val2;

        while (inp)
        {
            inp >> val1;
            inp >> val2;
        }

        std::cout << val1 << " " << val2 << std::endl;
    }

    int main()
    {       


            std::ifstream inp("C:\\somefolder\\ans.txt");

            printcontents(inp);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2020-01-09
    相关资源
    最近更新 更多