我有一个包含以下值的文本文件:
2013 05 27 15 52 02.049824 231.401 0.022 49.738 2013 05 27 15 52 02.668822 229.814 0.019 49.738 2013 05 27 15 52 03.283705 228.528 2.599 49.726 2013 05 27 15 52 03.898469 230.140 2.576 49.751
Column1 = date,Column2 = Month,Column3 = Day,Column4 = Hour,Column5 = Minute,Column6 = Seconds,Column7 = Voltage(Vrms),Column8 = Current(Irms),Column9 = Frequency(Hz)。
我必须开发一个程序,在24小时内分析这些时间采样的电压和电流测量值,并找出所用的总能量,平均和峰值功耗以及24小时内每小时使用的能量。
我该如何做呢? 我还必须包括至少一种数值积分技术 文件数据包含上述格式的5万多行。
我如何输入数据?这就是我的尝试。
using namespace std;
class DataTable{
public:
int year;
int month;
int day;
int hour;
int minute;
double seconds;
double voltage;
double current;
double frequency;
};
int main(){
DataTable Data;
ifstream DataFile("Data.txt");
if (!DataFile)
cout << "Unable to open" << endl;
int year1, month1, day1, hour1, minute1;
double seconds1, voltage1, current1, frequency1;
while(DataFile >> year1 >> month1 >> day1 >> hour1 >> minute1 >> seconds1 >> voltage1 >> current1 >> frequency1)
{
Data.year = year1;
Data.month = month1;
Data.day = day1;
Data.hour = hour1;
Data.minute = minute1;
Data.seconds = seconds1;
Data.voltage = voltage1;
Data.current = current1;
Data.frequency = frequency1;
}
return 0;
}
答案 0 :(得分:0)
我如何输入数据?
您希望拥有std::vector<DataTable>
,您可以在其中存储在while循环中填充的Data
个实例的副本:
int main() {
ifstream DataFile("Data.txt");
if (!DataFile) {
cout << "Unable to open" << endl;
return -1;
}
int year1, month1, day1, hour1, minute1;
double seconds1, voltage1, current1, frequency1;
std::vector<DataTable> records;
while(DataFile >> year1 >> month1 >> day1 >> hour1 >> minute1 >> seconds1 >>
voltage1 >> current1 >> frequency1) {
DataTable Data;
Data.year = year1;
Data.month = month1;
Data.day = day1;
Data.hour = hour1;
Data.minute = minute1;
Data.seconds = seconds1;
Data.voltage = voltage1;
Data.current = current1;
Data.frequency = frequency1;
records.push_back(Data);
}
// Do something with records ...
return 0;
}
答案 1 :(得分:0)
另一种选择是为结构重载operator>>
:
class DataTable{
public:
friend std::istream& operator>>(std::istream& inp, DataTable& dt);
int year;
int month;
int day;
int hour;
int minute;
double seconds;
double voltage;
double current;
double frequency;
};
std::istream& operator>>(std::istream& inp, DataTable& dt)
{
inp >> year;
inp >> month;
inp >> day;
inp >> hour;
inp >> minute;
inp >> seconds;
inp >> voltage;
inp >> current;
inp >> frequency;
return inp;
};
您的输入循环将如下所示:
std::vector<DataTable> data;
DataTable dt;
while (DataFile >> dt)
{
data.push_back(dt);
}
此范例的一个优点是数据结构可以在不影响输入循环的情况下进行更改。