做了一个从文本读取数据的函数,但结果不对,请,错哪
做了一个从文本读取数据的函数,但结果不对,请高手指点,错哪
#include <iostream>
#include <fstream>
#include <sstream>
#include <math.h>
#include <iomanip>
#include <string>
#define H 1500//行数
#define L 23//列数
using namespace std;
int main()
{
void read(string file,string FUZAI[H][L]);
string temp[12];
temp[0]="201101";
string FUZAI1101[H][L],FUZAI[H][L];
read(temp[0],FUZAI);
FUZAI1101[H][L]=FUZAI[H][L];
return 0;
}
void read(string file,string FUZAI[H][L])
{
int i=0;
int j=0;
int m=0;
int n=0;
//初始化
for(m=0;m<H;m++)
{
for(n=0;n<L;n++)
{
FUZAI[m][n]="空";
}
}
//从文本文件中读取数据
ifstream fin;
fin.open(file.c_str());
for(i=0;i<H;i++)
{
for(string s;getline(fin,s);)
{
j=0;
istringstream sin(s);
for(string ia;sin>>ia;)
{
j++;
FUZAI[i][j]=ia;
if(i==L-1){break;}
}
}
}
fin.close();
}
------解决方案--------------------
楼主,我的意思不是数组不能做参数,而是说数组做参数的时候好像不能那样写.对你的函数做了简单的注释:
#include <iostream>
#include <fstream>
#include <sstream>
#include <math.h>
#include <iomanip>
#include <string>
#define H 1500//行数
#define L 23//列数
using namespace std;
int main()
{
void read(string file,string FUZAI[H][L]);
string temp[12];
temp[0]="201101";
string FUZAI1101[H][L],FUZAI[H][L];
read(temp[0],FUZAI);
FUZAI1101[H][L]=FUZAI[H][L];
return 0;
}
void read(string file,string FUZAI[H][L])
{
int i=0;
int j=0;
int m=0;
int n=0;
//初始化
for(m=0;m<H;m++)
{
for(n=0;n<L;n++)
{
FUZAI[m][n]="空";
}
}
//从文本文件中读取数据
ifstream fin;
fin.open(file.c_str());
for(i=0;i<H;i++)
{
for(string s;getline(fin,s);)
{
j=0;
istringstream sin(s);
for(string ia;sin>>ia;)
{
j++;
FUZAI[i][j]=ia;
if(i==L-1){break;}
}
}
}
fin.close();
}
------解决方案--------------------
楼主,我的意思不是数组不能做参数,而是说数组做参数的时候好像不能那样写.对你的函数做了简单的注释:
- C/C++ code
#include <iostream> #include <fstream> #include <sstream> #include <math.h> #include <iomanip> #include <string> #define H 15//行数 #define L 23//列数 using namespace std; void read(string file,string FUZAI[][L]); int main() { string temp="201101.txt"; string FUZAI[H][L];//,FUZAI1101[H][L] //read(temp,FUZAI); //FUZAI1101[H][L]=FUZAI[H][L]; return 0; } void read(string file,string FUZAI[][L])//参数应写成string FUZAI[][L],而不是string FUZAI[H][L] { int i=0; int j=0; int m=0; int n=0; //初始化 for(m=0;m<H;m++) { for(n=0;n<L;n++) { FUZAI[m][n]="空"; } } //从文本文件中读取数据 ifstream fin; fin.open(file.c_str()); for(i=0;i<H;i++) { for(string s;getline(fin,s);)//此处只需一句getline(fin,s);即可,不要循环.你本意是一次读一行,但循环就是一次把所有的都读取了. { j=0; istringstream sin(s); for(string ia;sin>>ia;)//用sin>>ia将一行字符串中按空格区分一个一个传递给ia //问题是你的日期中间似乎有空格所以,一个2011-01-09 18:30:00可能会被分成两部分 { //j++; 此处的j++应该移到后面去 FUZAI[i][j]=ia; if(i==L-1){break;}//此处貌似应该不是i而是j. j++; } } } fin.close(); }
------解决方案--------------------
还有个小问题就是,数组赋值不是这样FUZAI1101[H][L]=FUZAI[H][L];
而是要循环,把每个元素都赋值一遍.
我一时也想不到年月日和时分秒之间的空格该如何处理,楼主你可能需要跟提供这个txt档的人商量一下,看他能不能将每个元素后面增加一个分隔符例如,这个分隔符不能在表元素里面出现.
如果txt档的格式不能改变的话,楼主可能要写一个函数,专门处理每一行字符串里的空格,哪些是分隔符,哪些不是.
------解决方案--------------------
另外,楼主你提供的txt档中加上编号,应该是24列.不是23.
关于年月日和时分秒之间的空格,楼主如果可以的话,将那几个时间比如最高负载率时间,分成最高负载率日期和最高负载率时刻两项,然后再进行处理.