Histogram help
May 6, 2016 at 10:49am UTC
Can Someone help me with a histogram that gets its values from an array in an input file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ARRAY_SIZE = 1000;
int get_array_values(int [], const int , ifstream&)
int main()
{
string filename;
system("cls" );
system("pause" );
ifstream ifile;
while (!ifile.is_open())
{
system("cls" );
cout << endl << endl;
cout << endl << endl;
cout << " Please enter the name of the input file" << endl
<< " in which the list of numbers is found." << endl;
cout << " " ;
getline(cin, filename);
ifile.open(filename += ".txt" );
if (!ifile.is_open())
{
cout << endl << endl;
cout << " " ;
cout << filename << " did not open." << endl;
cout << endl << endl;
system("pause" );
}
}
int array1[ARRAY_SIZE];
int number_of_values = get_array_values(array1, ARRAY_SIZE, ifile);
for (int i = 0; i < number_of_values; ++i)
{
for (int m = 0; m < array1[m]; m++)
{
cout << "*" ;
}
cout << endl;
}
int get_array_values(int array1[], const int ARRAY_SIZE, ifstream& ifile)
{
int size;
ifile >> size;
cout << endl << "Size = " << size << endl;
if (size > ARRAY_SIZE)
{
cout << endl << endl;
cout << "This is an invalid input File." << endl;
cout << "size was bigger than " << ARRAY_SIZE << endl;
exit(2);
}
for (int l = 0; l < size; l++)
{
ifile >> array1[l];
if (ifile.eof())
{
cout << endl << endl;
cout << "This is an invalid input File." << endl;
cout << "The size was larger than " << l << endl;
exit(3);
}
}
return size;
}
The current output looks like getting the amount values correct but the amount of * for each value only comes from the first value in the array
*****
*****
*****
*****
*****
But I want it to look like
In other words if i have an input file with the values of 5,2,1,4,3 it outputs
*****
*****
*****
*****
*****
instead of
which is what i want it to do
May 6, 2016 at 11:08am UTC
The problem is with your inner for loop.
try this:
1 2 3 4 5 6 7 8
for (int i = 0; i < number_of_values; ++i)
{
for (int m = 0; m < array1[i]; m++) // array[i] contains the number of stars
{
cout << "*" ;
}
cout << endl;
}
May 8, 2016 at 5:13am UTC
Thomas1965 that worked Thank you!
Topic archived. No new replies allowed.