I am writing a program in c++ which consists of a menu where the user has to choose between buying a plant or quitting. Each plant which the user can buy has an integer value associated with it.
The program has to write the integer value of the plant which the user bought in a text file and every plant which the user buys must br recorded in the tet file.
The first line of the file must contain the total no of items.
I am having a difficulty in calculating the total number of items bought and displaying it at the first line of the text file, so any help would be greatly appreciated.
# include <iostream>
# include <fstream>
# include <string>
usingnamespace std;
int addplant (int planttyp);
int main (void)
{
int noOfLines=1;
int textFile[noOfLines]; //an array which stores the contents of the file when it is read from
ifstream myFile2("stuff.txt");
ofstream myFile("stuff.txt");
if(!myFile)
{
cout<<"cannot open file"<<endl;
}
char str[255];
while(myFile2)
{
myFile2.getline(str,255);
textFile[noOfLines]=atoi(str); //reading the textfile
noOfLines++;
}
int total=0;
if(textFile[2]!=0)
total=textFile[2]+((noOfLines-1)/2);
myFile<<total<<endl;
int choice=0;
do{
cout<<"1: Buy plant seeds"<<endl;
cout<<"2: Quit"<<endl;
cin>>choice;
switch(choice)
{
case 1:
{
cout<<"Enter the type of plant you want "<<endl;
cout<<"0- strawberry "<<endl;
cout<<"1- wheat "<<endl;
cout<<"2- eggplant "<<endl;
cout<<"3- pumpkins "<<endl;
cout<<"4- rice "<<endl;
cout<<"5- blueberries "<<endl;
total++;
int typeP=-1;
cin>>typeP;
addplant(typeP);
break;
}
case 2: break;
default: cout<<"Choice does not exist"<<endl;
}
}while(choice!=2);
for(int i=1; i<noOfLines; i++)
{
myFile<<textFile[i]<<endl;
}
}
int addplant (int planttyp)
{
ofstream myFile;
myFile.open("stuff.txt", ios::app);
myFile<<planttyp<<endl;
myFile.close();
if((myFile.fail())||(planttyp<0)||(planttyp>5)) return -1; elsereturn planttyp;
}