我正在尝试从一个名为的文本文件中读取数据,该文件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}
我希望程序将数据读取到称为struct的数组中,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
}
如果您需要进一步的指导,请告诉我,但我想看看您如何处理它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句