class SalesData{
private:
ifstream inputfile;
ofstream outputfile;
vector<int> salesrecords;
public:
void loadDataFromFile(string filename){
ifstream infile;
infile.open ("sales.txt");
string line;
//this loop will read the file line by line and store each value in the sales records vector by changing that reading string value to int
while (getline(infile, line))
{
//This declares the character array to store the value of reading line
char arr[line.size()];
//This copies the string into character array
for(int i=0;i<line.size();i++)
arr[i] = line[i];
//This converts the character array into integer
int val=atoi(arr);
//This stores the above converting value into sales records
salesrecords.push_back(val);
}
//This closes the file
infile.close();
}
void saveBarChartToFile(string filename){
ofstream myfile;
//This opens the file
myfile.open ("graph.txt");
//This writes the header to the file
myfile<<"SALES BAR CHART\n(each * equals £100)"<<endl;
// cout<<"SALES BAR CHART\n(each * equals £100)"<<endl;
for(int i=0;i<salesrecords.size();i++){
//because 1 * is 100 pounds, we divide the value by 100 to get the number of stars for that value
int n=salesrecords[i]/100;
//This writes to the file the store number
myfile<<"Store "<<i+1<<": ";
// cout<<"Store "<<i+1<<": ";
//This writes to the file the number of stars
for(int j=0;j<n;j++){
myfile<<"*";
// cout<<"*";
}
myfile << "\n";
// cout<<endl;
}
//This makes sure the file closes
myfile.close();
According to the comments that come with the code, infile is read line by line into a char array which is then converted to an int used std::atoi
However it appears that the file contains only numbers in which case you can read it directly into a temporary integer variable and then push_back this variable into std::vector<int> salesrecords:
1 2 3 4 5 6 7 8
int temp{};//temporary int variable
while (infile >> temp)//read file into temp
{
if (infile)//make sure file is still open
{
salesrecords.push_back(temp);//populate salesrecords
}
}