M.V. Studio C++ - 2D Arrays NOT working with Files - c++

I am new to C++ (so, please forgive me for my C++ atrocities) and am asking for help once again to the helpful people at stack Overflow. I have to create a 2D Array program that reads from 2 files, one named after the Months of the year, and the other being a table of integer values.
I have four functions that break off of main in a switch menu. Function One should display the whole chart with the months going down the first column.
Months && Values. So, basically the months are all in the first column[0] and the values line up adjacent to the months (there will be some added flair to the top most row to give a description of what the values are, but I am sure I can figure that part out)
Then the second function takes all the values in column 1 & 2 (so not [0] because that's the months).
Then my third function takes columns [4] & [5] and adds them up and displays the totals, with the months to left of the values.
My fourth and final function will allow a user to input a given month and display the value display in the 1 first column after the months.
All of my output is never ending 0's.
Please if you could give me any tips/advice/code examples/anything would be greatly appreciated, and I thank you for taking your time to read this garbage code, so that I can hopefully get better at programming! Here is my code, I have not finished it yet since I keep having loop errors that display 0's when I try to ask the program to display one of the four options.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
// Global Array Size
const int ROWS = 12, COLUM = 9;
int parkChart[ROWS][COLUM];
//Function Prototypes
void displayCodes(const int[][COLUM], int);
int totalRecNonRec(const int[][COLUM], int rows, int total);
int tentRvByMonth(const int[][COLUM], int);
int displayMonth(const int[][COLUM], int, string);
int main()
{
// Define variables
const int DISPLAY = 1, REC_NONREC = 2, TENT_RV = 3, PER_MONTH = 4;
int response, total = 0;
string month;
ifstream inputFile;
inputFile.open("Months.txt");
ifstream inputFile2;
inputFile2.open("Vistors.txt");
cout << "Visitors to National Park" << endl;
// Do While Loop to display the menu
cout << "Enter 1 to display data" << endl;
cout << "Enter 2 to display total number of recreation and non-recreational visitors" << endl;
cout << "Enter 3 to display total tent and RV campers by month" << endl;
cout << "Enter 4 to display the number of recreational visitors for a certain month" << endl;
cout << "Enter any other number to exit" << endl << "\n";
cin >> response;
do
{
switch (response)
{
case(DISPLAY):
{
inputFile;
inputFile2;
displayCodes(parkChart, ROWS);
break;
}
case(REC_NONREC):
{
totalRecNonRec(parkChart, ROWS, total);
break;
}
case(TENT_RV):
{
tentRvByMonth(parkChart, ROWS);
break;
}
case(PER_MONTH):
{
displayMonth(parkChart, ROWS, month);
break;
}
default:
{
// Closes the file and exits
inputFile.close();
exit(0);
}
}
} while (response == 1 || response == 2 || response == 3|| response == 4);
system("pause");
return 0;
}
// Four Functions
// Display Function
void displayCodes(const int parkChart[][COLUM], int ROWS)
{
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLUM; col++)
{
cout << parkChart[row][col] << "\t ";
}
cout << endl;
}
}
// Totals/Display Rec. & Non Rec. Visitors to the park + adds all months for visitors (must equal 3,350,493)
int totalRecNonRec(const int parkChart[][COLUM], int rows, int total)
{
// for loop that adds all the elements in [0-11,1]&&[0-11,2]
for (int col = 0; col < 1; col++)
{
total = 0;
for (int row = 0; row < ROWS; row++)
total += col;
cout << "The total number of recreational and non-recreational visitors: " << total << endl;
}
return total;
}
// Totals/Display Number of Tent & RV Campers by month (needs to add rv + tent) and show all months
int tentRvByMonth(const int parkChart[][COLUM], int rows)
{
for (int row = 0; row < ROWS; row++)
{
int total = 0;
for (int col = 4; col < 5; col++)
{
total += parkChart[row][col];
cout << parkChart[row][col] << " " << (col + 1) << endl;
}
cout << endl;
}
return 0;
}
int displayMonth(const int parkChart[][COLUM], int rows, string month)
{
// Prompt the user to enter a month/Display the number of Rec. Visitors for that month + Failsafe of non-months
// Need a for loop to search for the user given month, and then display the [month, 1]
cout << "Enter the month you want the number of recreational visitors\n";
getline(cin, month);
// search in first column of array
cout << "For the month of " << month << " there were " << " recreational visitors" << endl;
return 0;
}

Related

center the 1 at the top

#include <iostream>
using namespace std;
int main()
{
int rows, count, num, space;//creating four variables to use for the loops
cout << "Enter number of rows: ";//prompting the user to input the number of rows
cin >> rows;
while (rows < 1 || rows>9)
{
cout << "Entry must be between 1 and 9. Please Re-enter the number of rows" << endl; //Asking the user to re-enter the number of rows if it was an invalid input
cin >> rows;
}
for (count = 1; count <= rows; count++) //for function that loops from 1-how many rows the user puts in
{
for (space= 1; space < rows; space++) //inner loop that loops from 1 to how many rows the user put in and outputs a space
{
cout << " ";
}
for (num = 1; num <= (2*count-1); num++)//the last row of the pyramid has one less than two time sthe number the user input so this loops unitl that is hit
{
cout <<count << " ";
}
cout << "\n"; //outputs a new line
}
system("pause");
return 0;
}
Looking at the code and you are making a right Angled Triangle of numbers and guessing you need an Isosceles Pyramid of numbers
Refer the code below:
#include <iostream>
#include <string>
bool makeIsoscelesPyramid(const unsigned int& size)
{
if( size > 9 )
{
std::cout<<"Please Enter a positive number less than 9"<<std::endl;
return false;
}
for (int i = 0; i < size; i++)
{
//Number of Space to input
auto nSpace = size - ( i );
std::cout << std::string( nSpace, ' ');
//Times the number is repeated 1, 3, 5 ...
auto nTimesNumber = (i * 2) + 1;
//'1'+i could only print till 9
std::cout << std::string( nTimesNumber, '1'+i) << std::endl;
}
return true;
}
int main()
{
unsigned int nRows = 0;
bool bReturn = false;
do
{
std::cout << "Enter number of rows: \t";
std::cin>>nRows;
std::cout<<std::endl;
bReturn = makeIsoscelesPyramid(nRows);
} while( !bReturn );
return 0;
}
Output:
Enter number of rows: 5
1
222
33333
4444444
555555555

Not able to pass 2D array into a function without error message C++

I'm having trouble passing off the 2D array called "sales" to a function. Any idea what I'm doing wrong? I have C++ as an online class and my teacher is no help :( The error message I'm getting is:
no instance of overloaded function "getTotal" matches the argument
list as well as "COLS": undeclared identifier
getTotal function
does not take 2 arguments"
// Week 7 Assignment 2
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototypes
int getTotal(int[][COLS]);
// Global Variables
const int ROWS = 4;
const int COLS = 4;
const int NUM_DIVS = 5;
const int NUM_QTRS = 5;
int sales[ROWS][COLS];
int totalSales;
string division[NUM_DIVS] = { "North", "South", "East", "West", "Quarter Total" };
string quarters[NUM_QTRS] = { "Quarter 1", "Quarter 2", "Quarter 3", "Quarter 4" };
int total;
int main()
{
// Variables
cout << "This program will calculate information about sales during a year." << endl;
// Loops to fill the array
for (int count = 0; count < COLS; count++)
{
cout << "Please enter the sales for the North during Quarter " << (count + 1) << ": $";
cin >> sales[0][count];
}
for (int count = 0; count < COLS; count++)
{
cout << "Please enter the sales for the South during Quarter " << (count + 1) << ": $";
cin >> sales[1][count];
}
for (int count = 0; count < COLS; count++)
{
cout << "Please enter the sales for the East during Quarter " << (count + 1) << ": $";
cin >> sales[2][count];
}
for (int count = 0; count < COLS; count++)
{
cout << "Please enter the sales for the West during Quarter " << (count + 1) << ": $";
cin >> sales[3][count];
}
total = getTotal(sales, 4);
return 0;
}
// Function to get the total of everything in the array
int getTotal(int sales[][COLS])
{
int totAl = 0;
for (int count = 0; count < ROWS; count++)
{
for (int count = 0; count < COLS; count++)
totAl += sales[count][count];
return totAl;
}
}
First you are using COLS before it is defined and you can't do that, so you fix that by defining it first before attempting to use it:
// Global Variables
const int ROWS = 4;
const int COLS = 4;//this is defined here
int getTotal(int[][COLS]);//now the compiler knows what COLS is
Second your getTotal function, as your compiler rightly pointed out, only accepts one argument but you are passing two in total = getTotal(sales, 4);. I believe you are trying to pass the row size as the second argument but there is no need to do this in your case since all your functions can see the ROW definition being a global variable(in fact you are using ROWS inside getTotal function).
total = getTotal(sales); //this is enough to call the function
You should also note that there is no need to pass any parameter to your getTotal function since the array is declared global,though i would not advise you to use global variables this extensively in your code.
int getTotal();//function prototype without parameters since sales array is global variable
total = getTotal(); //call the function
You might also need to revisit the logic of you code inside getTotal since the current implementation, like defining the same variable count as both of your loops counter, will lead to unexpected result.

Using for loops to create a bar graph

CAN ONLY USE LOOPS & IF/ELSE Statements
So for my assignment I'm given this: Write a program with for loops that asks the user to enter today’s sales for five stores. The program should then display a bar graph comparing each store’s sales. Create each bar in the bar graph by displaying a row of asterisks. Each asterisk should represent $100 of sales.
So it should like:
Store 1: *****
Store 2: ***
Store 3: *******
etc.
I have most of it written up and everything displays properly except for my asterisks. I can't seem to get them to display. Also, I've searched around and there are answers to this, but all of them include arrays and we aren't allowed to use them in this exercise. Here's my code so far:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int sales = 0, sale = 0; //Identfy Variables
for (int i = 1; i <= 5; i++) {
cout << "Enter today's sales for Store " << i << ":" << endl;
cin >> sale;
sales += sale;
sales /= 100; //in a similar manner to +=, /= can be used for division.
}
cout << "SALES BAR CHART:" << endl;
cout << "Each * = $100" << endl;
for (int x = 1; x <= 5; x++) {
cout << "Store " << x << ": ";
for (int s = 0; s < sales; s++) cout << "*";
cout << endl;
}
return 0;
}
Try this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string star = "";
int sale;
for (int i = 1; i <= 3; i++)
{
cout << "Enter today's sales for Store " << i << ":" << endl;
cin >> sale;
star += "Store " + to_string(i) + string(":");
for(int j= 0; j<sale/100; j++) {
star += "*";
}
star += "\n";
}
cout<<star;
return 0;
}
The problem with your code is that you do not store the data for each store individually. You have one variable called sales, which stores the sales of only the last store the end-user entered. All numbers the user enters before that get written over.
Since you have five stores, sales needs to be an array of five items:
int sales[5], total = 0;
Change your for loop to iterate 0 through 4, inclusive. Print (i+1) to end-users to stay one-based. Read sales numbers into sales[i] array element, then use it in the second loop to print your bar graph:
for (int i = 0 ; i != 5 ; i++) {
cout << "Enter today's sales for Store " << (i+1) << ":" << endl;
cin >> sales[i];
sales[i] /= 100;
total += sales[i];
}
...
// Now print your bar graph using a loop on i, and sales[i]
Your for loop is missing a definition of s:
for (int s; s < sales; s++)
should be:
for (int s = 0; s < sales; s++)
Without this explicit initialization, a variable s is declared, and memory is allocated for it, but its value remains whatever was left in memory from the last time that address was used. It's likely that this left over data was equivalent to an integer larger than sales, and thus your for loop wouldn't run, not even once.
As #dasblinkenlight mentioned, you have a singular variable that stores the "sales" of every store. Each store needs a separate variable, since each store is going to sell a different amount.
You already have the answers, I just want to add two options that would make printing the *'s easier:
using std::fill_n:
std::fill_n(std::ostream_iterator<char>(cout), sales, '*');
cout << endl;
using std::string's constructor overload (2):
cout << std::string(sales, '*') << endl;

User defined row, column output in C++

I have a 2 part question. I am showing a user defined array. User input is # of rows, columns, and at what interval in the array to put a symbol.
I cannot get an output of the default symbol ****.
Where do I need to insert the interval input to adjust the array accordingly? Inside the function itself or define another function to do this?
I am looking for this result. Input = 1 (row), 4 (columns), 2 (interval). Output would be **?*.
Here is what I have so far.
#include <iostream>
using namespace std;
int rows = 0, columns = 0, interval = 0;
char symbol;
void Display(int rows = 0, int columns = 0, int interval = 0, char symbol = ('*'));
int main()
{
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter the number of columns: ";
cin >> columns;
cout << "Enter the number of the question mark interval: ";
cin >> interval;
cout << "\n";
cout << "How many rows do you want? " << rows << "\n";
cout << "How many columns do you want? " << columns << "\n";
cout << "How far between question marks? " << interval << "\n";
Display(rows, columns, interval, symbol);
return 0;
}
void Display(int rows, int columns, int intervals, char symbol)
{
for (int y = 1; y <= rows; y++)
{
for (int x = 1; x <= columns; x++) {
cout << symbol;
}
cout << endl;
}
system("pause");
}
The problem is you never assigned * to symbol.
Change
char symbol;
to
char symbol = '*';
Did you know about the disadvantages of global variables. The sooner you learn about the cons the better. Here is a starting point.
Modify the Display function as below:
void Display(int rows, int columns, int intervals, char symbol)
{
for (int y = 1; y <= rows; y++)
{
for (int x = 1; x <= columns; x++) {
if ((x % (interval + 1)) == 0) //<--since you want after every intervals, just do a mod operation
cout << "?";
else
cout << symbol;
}
cout << endl;
}
system("pause");
}
Here is the working example.

Summing all the numbers in a matrix revised

Hello I had recently asked a question about how to do the following:
Write a function that sums all the integers in a matrix of integers using the following header:
const int SIZE = 4;
double sumMatrix (const double m [] [SIZE] , int rowSize, int columnSize) ;
Write a test program that reads a 4-by-4 matrix and displays the sum of all its elements. Heres a sample run:
Enter a 4by4 matrix row by row:
1 2 3 4 [Enter]
5 6 7 8 [Enter]
9 10 11 12 [Enter]
13 14 15 16 [Enter]
Sum of the matrix is 136
I tried to use all the suggestions I could but the problem maybe that I just need to go back to the basic and learn some basic things I have skipped over, but heres what I have so far. Corrections and solutions, and help in any form would be highly appreciated.
#include <iostream>
using namespace std;
const int COLUMN_SIZE = 4;
int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}
return total;
}
int main()
{
int m[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
cout<< "Sum of the matrix"<< sum(m,4) << endl;
return 0;
}
The read function that you need will look almost the same as your print function:
void read(const int a[] [COLUMN_SIZE], int rowSize)
{
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
cout << "Enter number for [" << row << "][" << column << "]: ";
cin >> a[row][column];
}
}
}
(As a footnote: if you can generalise the looping and have one function that you pass 'read' or 'sum' to you're well on your way to being awesome)
edit: guess I didn't read the 'row by row' bit of the question. shrug.
Three years later, haha, but you can enter cols elements separating them with spaces and use enter to get elements of other row.
Improving your code. Just see and understand. A didactic program is better than a thousand words :p
#include <iostream>
using namespace std;
const int COLUMN_SIZE = 4;
int sum(const int a[] [COLUMN_SIZE], int rowSize)
{
int total = 0;
for (int row = 0; row < rowSize; row++)
{
for (int column = 0; column < COLUMN_SIZE; column++)
{
total += a[row][column];
}
}
return total;
}
void showmatrix(const int a[] [COLUMN_SIZE], int rowSize, const char *name)
{
int row_index, col_index;
cout<< name << " [" << rowSize << "][" << COLUMN_SIZE << "] =" << endl;
for(row_index = 0; row_index < rowSize; row_index++)
{
for(col_index = 0; col_index < COLUMN_SIZE; col_index++)
{
if(col_index == 0)
{
if(row_index ==0)
{
cout<< "\t /";
}
else if(row_index == rowSize - 1)
{
cout<< "\t \\";
}
else
{
cout<< "\t|";
}
}
cout<< "\t" << a[row_index][col_index];
if(col_index == 3)
{
if(row_index ==0)
{
cout<< "\t\\";
}
else if(row_index == rowSize - 1)
{
cout<< "\t/";
}
else
{
cout<< "\t |";
}
}
}
cout<< endl;
}
cout<< endl;
}
int main()
{
int m[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
int row_index, col_index;
cout<< "There is a stored matrix on that program. It is shown below: " << endl << endl;
showmatrix(m, 4, "Stored_Matrix");
cout<< "The sum of elements of that stored matrix is: "<< sum(m,4) << endl << endl;
cout<< "Now, let's enter another 4 x 4 matrix." << endl << endl;
cout<< "(Note: You can use <space> character to separate column elements or <enter>" << endl;
cout<< "key to enter a new row.)" << endl;
cout<< "(Note 2: Really, you can use both to separate each one of the 16 matrix" << endl;
cout<< "elements, but do not enter more than that or the program will do some error)." << endl << endl;
for(row_index = 0; row_index < 4; row_index++)
{
for(col_index = 0; col_index < 4; col_index++)
{
cin>> m[row_index][col_index];
}
}
cout<< endl;
cout<< "The entered matrix is below:" << endl << endl;
showmatrix(m, 4, "Entered_Matrix");
cout<< "The sum of elements of that entered matrix is: "<< sum(m,4) << endl << endl;
//only to do not close console window on Windows
cout<< "Program ended." << endl << endl << "Press something to exit.";
cin.get();
cin.get();
return 0;
}
I hope you can use it on your reborn or after developing a time machine to use that idea on your 2010 homework.
As you use C++ Builder tag for that question, you can create a new console application and copy-paste the code above overwriting generated one. Use F9 to compile and run.