Write a C++ program that produces a bar chart showing the yearly income
of a small company starting 1990. The program reads the income figures (rounded to
the nearest $1,000) from a file called “income.txt”. For each year it should display the
date and a bar consisting of one star („*‟) for each $1,000.
Here is an example of how the chart might begin:
1990 **
1991 ****
1992 ***
1993 *****
Your program must have 2 functions: one function to get the length of the bar for a
given year and the other function draws one line of the chart.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool exists(string fileName)
{
bool ok = false;
ifstreamfile(fileName);
if (file.good())
{
ok= true;
file.close();
}
return ok;
}
int maxDigit(unsigned long int d)
{
int m = 0;
while (d > 0)
{
if (d % 10 > m)
{
m= d % 10;
}
d/= 10;
}
return m;
}
int countDigit(unsigned long int d)
{
int c = 0;
do
{
c++;
d/= 10;
}while (d > 0);
return c;
}
void buildHistogram(unsigned long int id, int digits[]) {
int maxd = maxDigit(id);
int len = countDigit(id);
for (int i = 1; i <= len; i++)
{
digits[len- i] = id % 10;
id/= 10;
}
}
void writeHistogram(ostream& os, unsigned long int id, int digits[])
{
int rows = maxDigit(id);
int len = countDigit(id);
os<< id << endl;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < len; j++)
{
if (digits[j] > i)
{
os<< '*';
}
else
{
os<< ' ';
}
}
os<< endl;
}
}
int main()
{
stringfileName;
stringchoice;
ifstreaminputFile;
ofstreamoutputFile;
unsigned long int id;
int digits[20];
/* Section 1 */
cout<< "Pleaseenter the name of the file you wish to open : ";
cin>> fileName;
inputFile.open(fileName);
if (inputFile.fail())
{
cout<< "Cannot open input file with such name." << endl;
return 1;
}
cout<< "Thefile is successfully opened." << endl;
/* Section 2 */
do {
cout<< "Pleaseenter the name of the file you wish to write : ";
cin>> fileName;
if (exists(fileName))
{
cout<< "Afile "<< fileName << "exists." << endl;
cout<< "Doyou want to continue and overwrite it? (y/n) : ";
cin>> choice;
if (choice == "y")
{
outputFile.open(fileName);
}
}
else {
outputFile.open(fileName);
if (!outputFile.good())
{
cout<< "Cannot open/create output file with such name." << endl;
return 1;
}
}
}while (!outputFile.good());
cout<< "Thefile is successfully opened." << endl << endl;
/* Section 3 */
inputFile>> id;
buildHistogram(id,digits);
/* Section 4 */
writeHistogram(outputFile,id, digits);
writeHistogram(cout,id, digits);
/* Section 5 */
inputFile.close();
outputFile.close();
return 0;
}