我正在尝试从名为 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;
}
编辑:为了专门处理 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 行
(直到没有更多行要读取 [EOF])。
inputstringstream
将所有出现的逗号和花括号替换为空格,以便于获取。
- 然后我们使用 vector 获取
iss
中剩余的所有数字。
- 然后为
struct fielddata
的每个成员赋予 vector 中每个相关位置的值。我们将前两个转换为整数,因为 vector 是 float
类型。
来自 this thread
First, make an ifstream
:
#include <fstream>
std::ifstream infile("thefile.txt");
Assume that every line consists of two numbers and read token by token:
int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
您只需创建 5 个变量,这些变量与您要放入每个结构中的数据类型相匹配。例如。 2 个 int
,3 个 float
。然后您只需按照上面概述的格式并将每个变量分配给结构的每个成员。
此外,建议在 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
}
如果您需要进一步的指导,请告诉我,但我想看看您如何处理它。
我是一名优秀的程序员,十分优秀!