c++ - 从 CSV 文件中读取数据并尝试将数据加载到由结构组成的向量中?
问题描述
我有一个名为“Sample.csv”的 .csv 文件,看起来像这样
0 60
1 61
2 62
3 63
我正在尝试将第一列读取为小时(int),将第二列读取为温度(double)。我将小时数和温度设置为一个名为“Reading”的结构,并有一个由这些读数组成的向量,称为“temps”。当我运行我的程序时,它不返回任何内容,并且 temps 的大小为 0。
我知道正在读取 csv 文件,因为我的错误消息没有弹出并且在玩弄它时我让它返回“0 ,0”一次。
struct Reading {
int hour;
double temperature;
};
vector<Reading> temps;
int main() {
int hour;
double temperature;
ifstream ist("Sample.csv");
if (!ist) {
cerr << "Unable to open file data file";
exit(1); // call system to stop
}
while (ist >> hour >> temperature) {
if(hour < 0 || 23 < hour) error("hour out of range");
temps.push_back(Reading{hour,temperature});
}
for (int i=0;i<temps.size();++i){
cout<<temps[i].hour<<", "<<temps[i].temperature<<endl;
}
cout<<temps.size();
ist.close();
}
我期待:
0, 60
1, 61
2, 62
3, 63
4
我的实际输出是:
0
解决方案
通过更正几个括号的位置,代码会产生预期的结果:
#include <iostream>
#include <fstream>
#include <sstream>
#include <cerrno>
#include <vector>
using namespace std;
struct Reading {
int hour;
double temperature;
};
vector<Reading> temps;
int main()
{
int hour;
double temperature;
ifstream ist("Sample.csv");
if (!ist) {
cerr << "Unable to open file data file";
exit(1); // call system to stop
}
while (ist >> hour >> temperature) {
if (hour < 0 || 23 < hour) {
std::cout << "error: hour out of range";
} else {
temps.push_back(Reading{hour, temperature});
}
}
for (int i = 0; i < temps.size(); ++i) {
cout << temps[i].hour << ", " << temps[i].temperature << endl;
}
cout << temps.size();
ist.close();
}
输出
0, 60
1, 61
2, 62
3, 63
4
Process finished with exit code 0
推荐阅读
- python - 在 Python3 中将整数数组转换为二进制:“TypeError:只能转换整数标量数组?”
- c++ - 如何将 .dat 中的值分配给 C++ 中的矩阵?
- python - 我想将两个文本变量和文本添加到 tkinter 中的标签小部件
- javascript - 带有下拉问题的 mCustomScrollBar
- python - 如何在树视图中的选定项目内向上或向下移动焦点
- python - 将来自 google collab 的训练结果保存为 CSV
- smooth-scrolling - locomotive.js 加载时平滑滚动更新()
- oauth - 关于跨域 OAuth 工作流程的安全问题
- java - javax.crypto.BadPaddingException:解密错误 RSA Android 应用程序和 Java 服务器
- javascript - module.exports = { fn } 是否与exports.fn = fn 相同