首页 > 解决方案 > 二进制“<<”:未找到采用“temperature_stats”类型右侧操作数的运算符(或没有可接受的转换),第 36 行

问题描述

我收到此代码的两个错误,这两个错误是:

没有运算符 "<<" 匹配这些操作数 [第 36 行]

二进制“<<”:未找到采用“temperature_stats”类型的右侧操作数的运算符(或没有可接受的转换)[第 37 行]

但是,它试图输出函数的结果,所以我不知道是什么真正导致了问题。

对于代码,假设文件位置正确且工作正常

#include <fstream>
#include <iostream>

using namespace std;

struct temperature_stats {
    string month;
    int hi_temp = 0;
    int low_temp = 0;
};

temperature_stats months_per_year[12];

void loadData(ifstream& inFile, temperature_stats[], int& size);
temperature_stats averageHigh(temperature_stats array[], int size);
temperature_stats averageLow(temperature_stats array[], int size);

temperature_stats averageHigh(temperature_stats array[], int month) {
    // this function calculates and returns the high temperature and the corresponding month of the year
    return array[month];
}

temperature_stats averageLow(temperature_stats array[], int month) {
    // this function calculates and returns the low temperature and the corresponding month of the year
    return array[month];
}

int main() {
    ifstream inFile;

    int rows = 12;

    loadData(inFile, months_per_year, rows);

    for (int j = 0; j < 12; j++) {
        cout << "The highest temperature recorded in the month of " << months_per_year[j].month << " was "
            << averageHigh(months_per_year, j) << endl;
    }

    inFile.close();

}

void loadData(ifstream& inFile, temperature_stats[], int& size) {
// this function reads and sorts data from a text file
    inFile.open(); // file location, can be interchangable if needed

    if (!inFile) {
        cout << "404 ERROR: FILE NOT FOUND\n" << endl; // debug line
    }

    if (inFile) {
        cout << "FILE FOUND!\n" << endl; // debug line
    }

    for (int i = 0; i < 12; i++) {
        inFile >> months_per_year[i].month >> months_per_year[i].hi_temp >> months_per_year[i].low_temp;
        cout << months_per_year[i].month << " " << months_per_year[i].hi_temp << " " 
            << months_per_year[i].low_temp << endl; // debug line
    }
}

标签: c++

解决方案


您尝试打印的结果是一个结构,而 C++ 不知道如何自动执行复杂的用户定义值。

<<真的不是魔法,它实际上是一种提供写入输出流 ( ostream) 的函数的聪明方法,您可以重载运算符以打印您的类型,如下所示:

std::ostream& operator<<(std::ostream& os, const temperature_stats& ts) {
    os << "Temperature: "
      << ts.month
      << " low: " << ts.low_temp
      << " high: " << ts.hi_temp;
    return os;
}

推荐阅读