#include <iostream>
#include <math.h>
#include <sstream>
#include <fstream>
using namespace std;
int itemlist=0;
string x;
int randocount=0;
int c=0;
int r = 0;
int itemlistdec()
{
cout<<"How many items would you like to input?";
cin>>itemlist;
try
{
if (itemlist<1)
throw itemlist;
else
return itemlist;
}
catch (const int caughtlist)
{
cout<<"You cannot type less than 1 item ";
cout<<"\n";
itemlistdec();
}
}
int main() {
itemlistdec();
string item[4][itemlist];//declares item and that columns equal to itemlist whose content is declared right above
for (int c=0;c<itemlist;c++)
{
for (int r=0;r<3;r++) //DETERMINES WHERE EACH RECORD GOES
{
if (r==0)
{
cout<<"Please enter the name of the item ";
}
if (r==1)
{
cout<<"Please input the buying price\n";
}
if (r==2)
{
cout<<"Please input the selling price\n";
}
cin>>item[r][c];
}
}
int calc[3][itemlist];//declaring calc and itemlist
for (int r = 0;r<itemlist;r++)
{
istringstream(item[1][r])>>calc[0][r]; //TAKES BUYING PRICE INTO INT ARRAY FOR CALCULATION
}
for (int r = 0;r<itemlist;r++)
{
istringstream(item[2][r])>>calc[1][r]; //TAKES SELLING PRICE INTO INT ARRAY FOR CALCULATION
}
for (int fart = 0;fart<itemlist;fart++)
{
calc[2][fart] = calc[1][fart] - calc[0][fart]; //REPEATS CALCULATION FOR PROFIT UNTIL ITEMLIST IS REACHED
}
for (int r = 0;r<itemlist;r++)
{
stringstream ss;
ss<<calc[2][r]; //CONVERTS BOTH PROFIT VALUES INTO STRINGS
item[3][r] = ss.str();
}
ofstream myfile;
myfile.open ("C:\\Users\\ENVY 14\\Documents\\Plankarraywritten.txt");
myfile<<"______________________________________________\n"; //DISPLAYS OUTPUT IN TABLE FORM
myfile<<"Item\t\tBuying Price\t\tSelling Price\t\tProfit\n";
for (int c=0;c<itemlist;c++)
{
for (int r=0;r<4;r++)
{
myfile<<item[r][c]<<"\t\t";
if (r==1)
{
myfile<<"\t";
}
if (r==2)
{
myfile<<"\t";
}
if (r==3)
{
myfile<<"\n";
}
randocount++;
}
}
myfile.close();
ifstream myifile;
myifile.open ("C:\\Users\\ENVY 14\\Documents\\Plankarraywritten.txt");
for (int read=0;read<randocount;read++)
{
myifile>> x;
cout<<x;
}
myifile.close();
return 0;
}
答案 0 :(得分:1)
首先,代码甚至无法工作,因为你无法初始化这样的数组。正如您的编译器可能会告诉您的那样,itemlist必须是一个常量值。修复一些STL容器,如vector或在堆上分配数组。还请删除不必要的异常处理:
try
{
if (itemlist<1)
throw itemlist;
else
return itemlist;
}
catch (const int caughtlist)
{
cout<<"You cannot type less than 1 item ";
cout<<"\n";
itemlistdec();
}
简单的if语句就足够了......
你不能在这里发布一些甚至无法编译的真正基本代码。
(同样命名一个变量&#39; fart&#39;有问题,长大了)
答案 1 :(得分:0)
首先检查你的代码,你的代码甚至没有编译。 itemlist 必须具有常量值才能初始化 item 数组。使用向量或某个STL容器来存储项数组的变量。
然后使用 getline 从文件中逐行阅读。