将文件列读取到数组中

reading file columns into an array

本文关键字:数组 读取 文件      更新时间:2023-10-16

我是编程新手,所以我有一个基本问题。我目前有一个365行的文本文件。。。一年中每天一行。这是文件的前四行:

2003 1 1 18 0 -1 36 50 46
2003 1 2 16 3 -1 43 56 52
2003 1 3 19 7 -1 42 56 49
2003 1 4 14 3 -1 42 58 50

我最终不得不使用一个特殊的库来绘制这些图,但首先我想将每列的数据放入一个数组中。这是我的代码的一部分,我试图做到这一点。

#include "library.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
ifstream in;
int yr[364], mo[364], day[364], windSpeed[364], precip[364], snowDepth[364], minTemp[364], maxTemp[364], avgTemp[364];
void main() {
    make_window(800, 800);
    set_pen_color(color::red);
    set_pen_width(8);
// open file, read in data
    in.open("PORTLAND-OR.TXT");
    if (in.is_open()) {
        // read each column into an array
        for (int i = 0; i < 364; i++) {
            in >> yr[i] >> mo[i] >> day[i] >> windSpeed[i] >> precip[i] >> snowDepth[i] >> minTemp[i] >> maxTemp[i] >> avgTemp[i];
            cout << mo[i] << "    " << day[i] << endl;
        }
        in.close();
    }
    else {
        cout << "error reading file" << endl;
        exit(1);
    }
}

当我试图打印出第二列和第三列(月和日)中的所有值时,它从3月8日(3月8)到12月31日(12月31)开始打印。我需要它从1月1日一直打印到12月31日。前两个月的价值没有打印出来是有原因的吗?

下面是一个非常愚蠢的仅主程序,它用现有的读取代码读取文件,然后再次打印出来。我在代码中嵌入了一个运行注释,其中包含了您应该考虑做的事情。

基本上,这就是我昨天在循环中所说的,不显示文件中的所有数据条目

#include <iostream>
#include <fstream>
using namespace std; // bad! Avoid doing this in real life.
int yr[364], 
    mo[364], 
    day[364], 
    windSpeed[364], 
    precip[364], 
    snowDepth[364], 
    minTemp[364], 
    maxTemp[364], 
    avgTemp[364]; // bad! define a structure instead

/* Example:
struct stats
{
    int yr; 
    int mo; 
    int day; 
    int windSpeed; 
    int precip; 
    int snowDepth; 
    int minTemp; 
    int maxTemp; 
    int avgTemp;
};
struct stats statistics[364]; // bad! use a std::vector instead
std::vector<stats> statistics; 
*/
int main()
{
    // removed all the windowing stuff.
    ifstream in;
    in.open("PORTLAND-OR.TXT");
    if (in.is_open())
    {
        // read each column into an array
        for (int i = 0; i < 364; i++)
        { // what do you do if the file ends early or contains bad information?
            in >> yr[i] >>
                  mo[i] >>
                  day[i] >>
                  windSpeed[i] >>
                  precip[i] >>
                  snowDepth[i] >>
                  minTemp[i] >>
                  maxTemp[i] >>
                  avgTemp[i];
        }
        in.close();
    }
    else
    {
        cout << "error reading file" << endl;
        return 1;
    }
    // printing out all the stuff that was read 
    for (int i = 0; i < 364; i++)
    {
        cout << yr[i] << "," <<
                mo[i] << "," <<
                day[i] << "," <<
                windSpeed[i] <<  "," <<
                precip[i] <<  "," <<
                snowDepth[i] <<  "," <<
                minTemp[i] <<  "," <<
                maxTemp[i] <<  "," <<
                avgTemp[i] << endl;
    }
}