c++ - 二进制“<<”:未找到采用“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++ 不知道如何自动执行复杂的用户定义值。
这<<
真的不是魔法,它实际上是一种提供写入输出流 ( 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;
}
推荐阅读
- php - 如何在 DomPDF 中安装自定义字体
- java - Log4j2 如何在自定义字段中从 MapMessage 中查找值
- php - 在 avada 主题融合 wordpress 中显示没有图像的投资组合列表
- android - 入队 onResponse 方法在 android 改造中返回空 response.body()
- excel - 数据透视表中的计数
- python - 寻找信号的峰值是不正确的
- python - TensorFlow 操作,在官方 API 中找不到
- postgresql - 将权限从用户转移到另一个用户
- c# - 无法为 .NetCore App 2.1 生成 ExtentReport?
- python - 访问被拒绝,在 Apache2 上运行 .py 尝试在 Apache2 上从 /opt 打开文件