好吧,我在编程方面不是很有经验,但我有一个任务要创建一个 c++ 程序,该程序使用数值方法根据混合物中每种物质的焓和百分比来计算三种物质混合物的温度.它基本上是 h = a1*T + a2*T^2 + ... 到 a6 的多项式。对于 H2O、H2 和 O2 中的每一个,这些系数 a1 到 a6 在表中给出。我的程序需要能够从 .dat 文件中读取物质名称和系数值,以便我可以将这些系数用于我的方程式。这就是我需要帮助的。我怎样才能让程序将物质名称和系数值输入到一个数组中,以便我可以在我的方程式中使用它们?对这部小说感到抱歉,但我试图提供尽可能多的背景信息。 下面正是我的 .dat 文件中的内容,以及我试图放入数组中的内容。首先是物质名称,然后是a1、a2等。
H2O 406598.40 440.77751 -.12006604 .000015305539 -.00000000072544769 -4475789700 H2 50815.714 9.9343506 -.000027849704 -.00000035332966 .000000000041898079 -14329128 O2 961091.64 199.15972 -.052736240 .00000897950410 -.00000000063609681 -318699310
this is my source code so far, but its not working, and I'm pretty lost.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
double myArray[21];
ifstream file("thermo2.dat");
if (file.is_open())
{
for (int i = 0; i < 21; ++i)
{
file >> myArray[i];
}
}
else
{
cout << "the file did not open";
}
for (int i = 0; i < 21; ++i)
{
cout << " " << myArray[i];
}
return 0;
}
谢谢!
编辑:开始尝试使用结构数组....我不断收到错误消息:没有匹配函数来调用“getline(std::ifstream&, double&, char)”。这是代码:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct Data
{
string species;
double a1, a2, a3, a4, a5, a6;
};
int main()
{
ifstream fin;
fin.open("thermo2.dat");
if (fin.fail())
{
cout << "Failed to open file" << endl;
}
Data * database = new Data[3];
string line;
for(int i = 0; i < 3; i++)
{
getline(fin, database[i].species, '\t');
getline(fin, database[i].a1, '\t');
getline(fin, database[i].a2, '\t');
getline(fin, database[i].a3, '\t');
getline(fin, database[i].a4, '\t');
getline(fin, database[i].a5, '\t');
getline(fin, database[i].a6, '\t');
}
system("pause");
return 0;
}
最佳答案
将您的结构声明为:
struct Data
{
string species;
double a[6];
}
阅读如下:
for(int i = 0; i < 3; i++) {
fin >> database[i].species;
for (int j = 0; j < 6; j++) {
fin >> database[i].a[j];
}
}
关于c++ - 将单词和数字的文件输入数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154377/