【发布时间】:2018-10-30 03:08:55
【问题描述】:
我是 C++ 新手,我的一项作业遇到了问题。目标是从如下所示的数据文件中加载数据。
item number date quantity cost per each
1000 6/1/2018 2 2.18
1001 6/2/2018 3 4.44
1002 6/3/2018 1 15.37
1001 6/4/2018 1 4.18
1003 6/5/2018 7 25.2
基本上,我需要使用数组计算每个日期使用的平均项目数,并使用成本进行一些其他计算。我真的很想从文件中加载数据并为方程式操作它。这是我目前所拥有的。
#include <cmath> //for math operations
#include <iostream> //for cout
#include <cstdlib> //for compatibility
#include <fstream>
#include <string>
using namespace std;
int main()
{
string date;
int EOQ, rp;
int count;
int itemnum[][];
double quantity[][];
double cost[][];
ifstream myfile;
string filename;
cout << "Data File: " << endl;
cin >> filename; // user enters filename
myfile.open(filename.c_str());
if(myfile.is_open())
{
cout << "file opened" << endl;
string head;
while(getline(myfile, head))
{
break; // so header won't interfere with data
}
while(!myfile.eof())
{ // do this until reaching the end of file
int x,y;
myfile >> itemnum[x][y] >> date >> quantity[x][y] >> cost[x][y];
cout << "The numbers are:" << endl;
for(count = 0; count < y; count++)
{
cout << itemnum[x][y] << endl;
break;
}
//cout << "Item: Reorder Point: EOQ: " << endl;
//cout << itemnum << " " << rp << " " << EOQ << endl;
break;
}
}
else
{
cout << "" << endl; //in case of user error
cerr << "FILE NOT FOUND" << endl;
}
cout << endl;
cout << "---------------------------------------------" << endl;
cout << " End of Assignment A8" << endl;
cout << "---------------------------------------------" << endl;
cout << endl;
system("pause");
return 0;
我还没有开始处理方程式,因为我仍然无法将文件加载到一个简单的数组中!!!
谢谢!
数据文件链接:https://drive.google.com/file/d/1QtAC1bu518PEnk4rXyIXFZw3AYD6OBAv/view?usp=sharing
【问题讨论】:
-
您可以发布您要加载的文件吗?我想我在问它是否是您帖子顶部所示的文本文件,或者它是否是某种二进制文件。
-
int itemnum[][];-- 这不是有效的 C++,也不是任何与此相似的行。 -
我故意将这些留空 - 我应该在括号中放置一个变量来表示 itemnum 还是 numbers?
-
@Nick 我应该在 itemnum 或 numbers 的括号中放置一个变量吗? -- 这是您遗漏的最重要的部分。您不能将运行时值放在括号中——数组的大小是固定的。你知道要阅读的最大项目数吗?如果没有,那么你不能使用数组——改用
std::vector。如果您确实知道最大条目数,则将读取的最大条目数放在括号中。您不能将它们留空——这不是有效的 C++。