C++如何读取txt文件两列数据并跳过首行存储以生成气温蜡烛图
C++ 温度蜡烛图作业实现方案
核心逻辑实现
1. 首行读取与留存
直接用std::getline读取文件第一行内容存入字符串变量,后续需要展示时直接输出该变量即可,无需重复读取文件。
2. 数值数据筛选存储
读完首行后,流指针会自动定位到第二行起始位置,直接循环读取每行的两个浮点数值,存入容器即可。
3. 蜡烛图生成
学生作业常用的轻量绘图方案是用matplotlib-cpp(Python matplotlib的C++封装),或者Qt的QCustomPlot模块,核心逻辑就是遍历存储的高低温数组,以1-12月为X轴坐标,每个X位置绘制从低温到高温的垂直柱体,填充颜色就得到蜡烛图。
可运行代码示例
#include <fstream> #include <string> #include <vector> #include <iostream> // 引入matplotlib-cpp头文件(需提前配置好库环境) #include "matplotlibcpp.h" namespace plt = matplotlibcpp; int main() { std::ifstream fin("temp_data.txt"); if (!fin.is_open()) { std::cerr << "无法打开数据文件" << std::endl; return -1; } // 读取首行标题留存 std::string file_title; std::getline(fin, file_title); // 读取高低温数据 std::vector<double> low_temps, high_temps, months; double low, high; int month_idx = 1; while (fin >> low >> high) { low_temps.push_back(low); high_temps.push_back(high); months.push_back(month_idx++); } fin.close(); // 输出展示首行内容 std::cout << file_title << std::endl; // 绘制蜡烛图 plt::figure_size(800, 600); // 逐月份绘制高低温柱体 for (int i = 0; i < months.size(); ++i) { // 绘制从低温到高温的垂直线段 plt::plot({months[i], months[i]}, {low_temps[i], high_temps[i]}, "r-", {{"linewidth", "10"}}); } plt::xlabel("月份"); plt::ylabel("温度(°F)"); plt::title(file_title); plt::xticks(months); // 同时展示图像和标题 plt::show(); return 0; }
高效实现优化点
- 读取文件前提前给存储温度的vector调用
reserve(12)(最多12个月数据),避免动态扩容开销 - 可以直接用结构化绑定处理存储的pair类型数据,代码更简洁
- 绘图时不要逐次调用plot接口,把所有线段的坐标预先整理成两个大数组,批量传入plot接口,渲染速度更快
内容的提问来源于stack exchange,提问作者nhamon321
相关产品推荐
相关产品推荐

