我正在尝试从名为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] = {};
,以便我能够使用数据创建显示。
#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;
}
答案 0 :(得分:0)
编辑:要专门处理OP的帖子中显示的输入类型(外面带花括号的逗号分隔符),这就是完成的操作。取自this thread
的想法//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
}
如果你需要进一步的指导,请告诉我,但我想知道你用它做了什么。