将文件列读取到数组中
reading file columns into an array
我是编程新手,所以我有一个基本问题。我目前有一个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;
}
}
相关文章:
- 从锯齿状数组读取
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- 如何按字符从文件到2D数组读取字符
- 双维数组读取错误
- 动态分配的数组C 读取句子并打印单词
- ESP8266异常在尝试从字节数组读取float时
- C++无法从 2D 字符串数组读取
- Win32 C/C++从字节数组读取BMP宽度和高度
- 在执行期间将大型多维数组读取和写入二进制文件并返回数组
- 从 BYTE 数组读取 32 位整数.VC++
- 从十六进制数组读取 Int
- 从十六进制数组读取双精度到向量
- 通过数组C++读取学生的成绩
- 使用迭代器数组读取稀疏信息
- 从文件到字符串再到数组读取数字
- 直接从数组读取时超出了绑定地址
- 转换为空指针后从char数组读取int值
- 动态数组读取
- 从字节数组读取类型的模板方法的问题
- 从文件中以单独的数组读取整数,每次一个数字,在c++中