[英]How do I read data from a text file into an array of struct
我正在嘗試從名為fields.txt
的文本文件讀取數據,該文本文件包含struct Fields
的成員。
{1, 0, 7.4, 39.5, 5.33784},
{3, 1, 4.6, 27.9, 6.06522},
{5, 2, 2.2, 12.5, 5.68182},
{8, 0, 14.5, 86, 5.93103},
{11, 1, 8, 43.8, 5.475},
{16, 2, 5.9, 37.7, 6.38983},
{22, 0, 12.7, 72, 5.66929},
{24, 1, 10.5, 63.2, 6.01905}
我希望程序將數據讀入稱為Fields fielddata[8] = {};
的結構數組中Fields fielddata[8] = {};
這樣我就可以使用數據創建顯示。
#include<iostream>
#include<fstream>
using namespace std;
std::ifstream infile("fields.txt");
int initialise(int field, int crop, float size, float yof, float yph);
struct Fields {
int Field;
int Crop;
float Size;
float Yof;
float Yph;
int initialise(int field, int crop, float size, float yof, float yph)
{
Field = field;
Crop = crop;
Size = size;
Yof = yof;
Yph = yph;
};
};
int main() {
Fields fielddata[8];
ifstream file("fields.txt");
if(file.is_open())
{
int a, b, i = 0;
float c, d, e;
while (infile >> a >> b >> c >> d >> e)
{
fielddata[i].Field = a;
fielddata[i].Crop = b;
fielddata[i].Size = c;
fielddata[i].Yof = d;
fielddata[i].Yph = e;
++i;
}
}
int highyph = 0;
cout << "Field\t" << "Crop\t" << "Size\t" << "YOF\t" << "YPH\t" << endl;
for (int i = 0; i < 8; i++) {
cout << fielddata[i].Field << "\t" << fielddata[i%3].Crop << "\t" << fielddata[i].Size << "\t" << fielddata[i].Yof << "\t" << fielddata[i].Yph << "\t" << endl;
}
for (int i = 0; i < 8; i++)
{
if (fielddata[i].Yph > highyph)
highyph = fielddata[i].Field;
}
cout << "The Field with the Highest Yield is " << highyph << endl;
system("Pause");
return 0;
}
編輯:要專門處理OP帖子中顯示的輸入類型(外面有花括號的逗號分隔符),就可以完成此操作。 這個主意
//Get each line and put it into a string
String line;
while (getline(infile, line)) {
istringstream iss{regex_replace(line, regex{R"(\{|\}|,)"}, " ")};
vector<float> v{istream_iterator<float>{iss}, istream_iterator<float>{}};
//Assigns each member of the struct to a member of the vector at the relevant position
fielddata[i].Field = static_cast<int>(v.at(0));
fielddata[i].Crop = static_cast<int>(v.at(1));
fielddata[i].Size = v.at(2);
fielddata[i].Yof = v.at(3);
fielddata[i].Yph = v.at(4);
++i;
}
基本上,這里發生的是:
String line
(直到不再有要讀取的行[EOF])。 inputstringstream
將所有出現的逗號和花括號替換為空格,以便於獲取。 iss
剩余的所有數字。 struct fielddata
每個成員一個值。 由於向量的類型為float
將前兩個轉換為整數。 從這個線程
首先,創建一個
ifstream
:#include <fstream> std::ifstream infile("thefile.txt");
假設每一行包含兩個數字,並逐個令牌讀取令牌:
int a, b; while (infile >> a >> b) { // process pair (a,b) }
您只需要創建5個變量即可與您要放入每個結構的數據類型匹配。 例如2 int
s,3 float
s。 然后,您只需遵循上面概述的格式,並將每個變量分配給該結構的每個成員。
同樣,建議在main的開頭而不是在中間初始化所有變量。
還有一點幫助可助您一臂之力。
int a, b, i = 0;
float c, d, e;
while (infile >> a >> b >> c >> d >> e)
{
fieldData[i].Field = a;
//Assign other struct members as you wish
++i; //Or use an inner for loop to do the incrementation
}
如果您需要進一步的指導,請告訴我,但我想看看您如何處理它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.