Hi everyone! I am currently a student taking a C++ programming course online. I was doing good until I hit the two dimensional arrays. Anyway, part of my assignment this week has to do with writing code that has a function searching a two deminsional array for the null terminator. I flat out just don't know where to begin. All the examples in my book search single dimensional arrays. I just don't understand enough to be able to use these examples. If anyone could either point me in the right direction with some examples or tutorials I would be really thankful.
Well, if you know how to iterate through a one-D-Array, than you have almost everything you need.
An array has the syntax myArrray[index]
So, in order to sort through it, you iterate the index and look if myArray[iterator] fits your condition.
With a two-D array, you do the same. Only difference is, you now have an array that looks like:
myArray [index1] [index2]
You see, you got two indices. So, applying what you know about one-D-arrays, you will see that you have to iterate through both indices. Which one you choose as inner and which as outer loop, does not matter. Usually, the one on the left gets to be the outer loop.
Or you use a pointer to look through the array, then you need only one loop. But judging from your post, that might just be a bit too much at the moment.
Thanks for the reply! Well, reading it, that makes since, but something happens when I try to go write it. I just can't put it together. Maybe some help if I show my code? Here is the part of the code with the search. I'm not sure if you'll need more, if you do, let me know.
void addBook(char bookTitle[][51], int Rows, int Cols);
{
//Function prototype
char searchList(bookTitle[], int, int);
char size = 51
//Search addbook array for null terminator
bookResult = searchList(bookTitle, SIZE, /0);
//If searchList returned -1, then array was full
if (bookResult == -1)
cout << "No more books may be added to the inventory.\n";
else
{
//Otherwise results contain an empty row
cout << "Please enter the Book Title \n";
cin >> bookTitle[][];
cout << "Please enter the ISBN number \n";
cin >> isbn[][];
cout << "Please enter the Author's name \n";
cin >> author[][];
cout << "Please enter the Publisher's name \n";
cin >> publisher[][];
cout << "Please enter the date the book is added to the "
cout << "inventory \n";
cin >> dateAdded[][];
cout << "Please enter the quanity of the book \n";
cin >> qtyOnHand[][];
cout << "Please enter the wholesale price of the book \n";
cin >> wholesale[][];
cout << "Please enter the retail price of the book \n";
cin >> retail[][];
}
return 0;
}
In the addBook function, you are calling searchList function to check what? If it does not return -1, is it suppose to add info to these arrays? I am not an expert but shouldn't there be indices's in the multidimensional arrays so the data is put into the correct place. I think calling just the name of the array references the first address where the first value is stored. I guess I am trying to understand where you are actually addBook?
dancer52 posted: Hi everyone! I am currently a student taking a C++ programming course online. I was doing good until I hit the two dimensional arrays.
I just posted an article I wrote titled Arrays Revealed.
You might read it since you believe there are two dimensional arrays in C++.
//This program is to display the main menu screen
#include <iostream>
#include "mainmenu.h"
#include <iomanip>
usingnamespace std;
char bookTitle[20][51];
char isbn[20][14];
char author[20][31];
char publisher[20][31];
char dateAdded[20][11];
int qtyOnHand[20];
double wholesale[20];
double retail[20];
int main()
{
int choice; //Menu choice
do
{
//Display the menu and get a choice
cout << "Serendipity Booksellers\n";
cout << "Main Menu\n";
cout << " \n";
cout << "1. Cashier Module\n";
cout << "2. Inventory Database Module\n";
cout << "3. Report Module\n";
cout << "4. Exit\n";
cout << " \n";
cout << "Enter your choice: \n";
cin >> choice;
//Validate and process the menu choice.
while (choice < 1 || choice > 4)
{
cout << "Please enter a number in the range 1-4.\n";
cin >> choice;
}
if (choice != 4)
switch (choice)
{
case 1: cashier();
break;
case 2: invMenu();
break;
case 3: reports();
break;
case 4: cout << "You selected item 4.\n";
break;
}
} while (choice != 4);
return 0;
}
//This function is to display the cashier screen
int cashier()
{
char date[8]; //Defining variables to be requested from user
int quantity;
char ISBN;
char title;
float price;
float subtotal; //Defining variables to be used to show information to user
float tax;
float total;
char again; //To hold Y or N input
do
{
//Getting variables defined above from user
cin >> setw(8) >> date;
cin >> quantity;
cin >> ISBN;
cin >> title;
cin >> price;
//Calculate the total amount
subtotal = quantity * price;
tax = subtotal * 0.06;
total = subtotal + tax;
cout << "Serendipity Booksellers\n";
cout << "Date: \n";
cout << "Qty ISBN Title Price Total \n";
cout << "_____________________________________________ \n";
cout << setprecision(2) << fixed;
cout << "Subtotal: " << setw(6) << subtotal << endl;
cout << "Tax: " << setw(6) << tax << endl;
cout << "Total: " << setw(6) << total << endl;
cout << "Thank You for Shopping at Serendipity! \n";
//Does the user want to process another transaction?
cout << "Do you want to process another transaction? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}
//This function is to display the inventory screen
int invMenu()
{
int choice; //Menu choice
do
{
//Display the menu and get a choice
cout << "Serendipity Booksellers\n";
cout << "Inventory Database \n";
cout << "1. Look Up a Book \n";
cout << "2. Add a Book \n";
cout << "3. Edit a Book's Record \n";
cout << "4. Delete a Book \n";
cout << "5. Return to the Main Menu \n";
cout << "Enter your choice: \n";
cin >> choice;
switch (choice)
{
case'1': void lookUpbook();
break;
case'2': void addBook();
break;
case'3': void editBook();
break;
case'4': void deleteBook();
break;
case'5': cout << "You selected item 5.\n";
break;
}
//Validate and process the menu choice.
while (choice < 1 || choice > 5)
{
cout << "Please enter a number in the range 1-5.\n";
cin >> choice;
}
} while (choice != 5);
return 0;
}
//Add stub functions for inventory database
void lookUpBook()
{
cout << "You selected Look Up Book.\n";
}
void addBook(char bookTitle[][51], int Rows, int Cols);
{
//Function prototype
char searchList(bookTitle[], int, int);
char size = 51
//Search addbook array for null terminator
bookResult = searchList(bookTitle, SIZE, /0);
//If searchList returned -1, then array was full
if (bookResult == -1)
cout << "No more books may be added to the inventory.\n";
else
{
//Otherwise results contain an empty row
cout << "Please enter the Book Title \n";
cin >> bookTitle[][];
cout << "Please enter the ISBN number \n";
cin >> isbn[][];
cout << "Please enter the Author's name \n";
cin >> author[][];
cout << "Please enter the Publisher's name \n";
cin >> publisher[][];
cout << "Please enter the date the book is added to the "
cout << "inventory \n";
cin >> dateAdded[][];
cout << "Please enter the quanity of the book \n";
cin >> qtyOnHand[][];
cout << "Please enter the wholesale price of the book \n";
cin >> wholesale[][];
cout << "Please enter the retail price of the book \n";
cin >> retail[][];
}
return 0;
}
void editBook()
{
cout << "You selected Edit Book.\n";
}
void deleteBook()
{
cout << "You selected Delete Book.\n";
}
//This function is to display the book info screen
int bookInfo()
{
cout << "Serendipity Booksellers\n";
cout << "Book Information \n";
cout << "ISBN: \n";
DisplayTheArray(isbn);
cout << "Title: \n";
DisplayTheArray(bookTitle);
cout << "Author: \n";
DisplayTheArray(author);
cout << "Publisher: \n";
DisplayTheArray(publisher);
cout << "Date Added: \n";
DisplayTheArray(dateAdded);
cout << "Quantity-On-Hand: \n";
DisplayTheArray(qtyOnHand);
cout << "Wholesale Cost: \n";
DisplayTheArray(wholesale);
cout << "Retail Price: \n";
DisplayTheArray(retail);
return 0;
}
//This function is to display the reports screen
int reports()
{
int choice; //Menu choice
do
{
//Display the menu and get a choice
cout << "Serendipity Booksellers\n";
cout << "Reports \n";
cout << "1. Inventory Listing \n";
cout << "2. Inventory Wholesale Value \n";
cout << "3. Inventory Retail Value \n";
cout << "4. Listing by Quantity \n";
cout << "5. Listing by Cost \n";
cout << "6. Listing by Age \n";
cout << "7. Return to the Main Menu \n";
cout << "Enter your choice: \n";
cin >> choice;
switch (choice)
{
case'1': void repListing();
break;
case'2': void repWholesale();
break;
case'3': void repRetail();
break;
case'4': void repQty();
break;
case'5': void repCost();
break;
case'6': void repAge();
break;
case'7': cout << "You selected item 7.\n";
break;
}
//Validate and process the menu choice.
while (choice < 1 || choice > 7)
{
cout << "Please enter a number in the range 1-7.\n";
cin >> choice;
}
} while (choice != 7);
return 0;
}
//Add stub functions for reports menu
void repListing()
{
cout << "You selected Inventory Listing.\n";
}
void repWholesale()
{
cout << "You selected Inventory Wholesale Value.\n";
}
void repRetail()
{
cout << "You selected Inventory Retail Value.\n";
}
void repQty()
{
cout << "You selected Listing By Quantity.\n";
}
void repCost()
{
cout << "You selected Listing By Cost.\n";
}
void repAge()
{
cout << "You selected Listing By Age.\n";
}
//*********************************************************
//This function is to search the bookTitle for an empty row
//*********************************************************
int searchList(int list[], int numElems, int value)
{
int index = 0;
int postion = -1;
bool found = false;
while (index < numElems && !found)
{
if (list[index] == value
{
found = true
position = index;
}
index++;
}
return position;
}
some of the errors:
Line 1 of the second post void addBook(char bookTitle[][51], int Rows, int Cols); /*this semicolon is an error*/
Line 173 of the second post: found = true /*missing semi-colon*/
Line 4 of second post: char searchList(bookTitle[], int, int);
This is a function declaration and should not be here inside the addBook function. It should be way up the top of the file where you declare the arrays or in mainmenu.h
The BookTitle parameter is also missing a type name like int which says what type of array it is.
Also it is declared as returing char but when you define it latere on it is returning an int
Line 5 of second post: char size = 51 missing semicolon at end of statement.
Line 5 and 8 of second post:
In line 5 you say size but in line 8 you say SIZE
Line 8 of second post: bookResult = searchList(bookTitle, SIZE, /0); should be bookResult = searchList(bookTitle, size, '/0'); note the single quoutes around the /0
Line 24 of second post: cout << "Please enter the date the book is added to the "; missing semicolon at end of statement
Line 34 of second post: return 0; is an error because a void function should not return a value.
Line 171 of second post: if (list[index] == value is missing a closing bracket )
In the SearchList function, the variableposition has been misspellt .
In the addBook function you are using a variable called bookResult Where is this variable declared?? You have not posted mainmenu.h so I can't see if it is there.
Can you post mainmenu.h ??
In my next post we will try and sort out the array problems
I will get the mainmenu.h file posted later tonight. Thanks for all the help! I'm going to update my code with your suggestions and try it again! Man, this is awesome!
int cashier();
int invMenu();
int bookinfo();
int reports();
int lookUpBook();
void addBook();
void editBook();
void deleteBook();
void repListing();
void repWholesale();
void repRetail();
void repQty();
void repCost();
void repAge();
I really want to thank you for all the help....I do have a couple of more questions. On the Line 4 of second post comment, would I take the entire line and move it to the mainmenu.h file? On the bookTitle missing a name, would it be char since the value stored in that field should be the title of books? And, last but not least, I don't have the bookResult defined. How would I define it? It's basically suppose to be the return of a blank row so that the user can add a new book to the inventory.
As I get deeper in this, I don't think I have a clear understanding on when to use int, char, float, double etc. in the code.
Yes, the whole line 4 needs to move out of the function. and declare bookTitle in the same way as you have done it in addbook()
bookResult is being set to the return value of searchList(). You are returning an int from this function so bookResult needs to be an int.
Generally using char, int, float etc:
You use them to tell the compiler what type of data a variable is (and its memory storage requirements), when declaring them in a function or class, or passing into or out of functions.
You should also put the parameters in your protoypes in mainmenu.h. This will allow the compiler to check to make sure you are passing the correct data types when you use these functions.
For example, line 6 should be
void addBook(char bookTitle[][], int Rows, int Cols);
I got the bookResult defined in the mainmenu.h file now. Now, it reads
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int cashier();
int invMenu();
int bookinfo();
int reports();
int lookUpBook();
char searchList(bookTitle[], char, char);
void addBook();
int bookResult;
void editBook();
void deleteBook();
void repListing();
void repWholesale();
void repRetail();
void repQty();
void repCost();
void repAge();
My question on adding the parameters in the prototypes is in the example you provided, bookTitle is just one of the values that is going to be defined when a new book is added, there are many more (like ISBN, price etc). Would I still define parameters like that?
int cashier();
int invMenu();
int bookinfo();
int reports();
int lookUpBook();
char searchList(char bookTitle[], char, char);
void addBook();
int bookResult();
void editBook();
void deleteBook();
void repListing();
void repWholesale();
void repRetail();
void repQty();
void repCost();
void repAge();code]
And the previous error I listed is gone. Thanks a lot for the help on that.
I'm still getting error's, but I've also added some code since I posted the complete code here.
One error I've gotten a few times and don't understand is this:
E2034 Cannot convert 'char[*][51]' to 'char *'
It is taking me to this part of the code that I added:
[code]int lookUpBook()
{
char titleResults;
//Function Prototype
char binarySearch(char [], char, char);
const char SIZE = 51;
//Get the title of the book to search for
cout << "Enter the title of the book you wish to search for. \n";
cin >> titleBook;
//Search for the title of the book
titleResults = binarySearch(bookTitle, SIZE, titleBook);
//If titleResults contain -1 the book was not found.
if (titleResults == -1)
cout << "That book was not found.\n";
else
//Otherwise titleResults contains the searched book
return int bookInfo;
cout << "Which values would you like to change? ";
cout << "ISBN, author, publisher, qtyOnHand, wholesale price, ";
cout << "or retail price?\n";
if
( cin >> char isbn;
}
Now, I haven't completed this part of the code, but basically what it's suppose to do is if the book the user is searching for is found, ask the user what field(s) it wants to update and then get that information from the user. I am confused on how to do that part right now (kinda why I stopped the other night). I am not sure how to list the fields (use a menu type option?) for the user to select or how to take their input and make sure it updates the right value for the right book.
Now, I still need to go back and review that part of the code and take some of the suggestions made and apply it.
Ok I have messed about with it and have made some changes as follows:
(anybody can feel free to comment).
1. Instead of hard coding the array sizes - I have used constint
2. Function prototypes have been moded from inside other functions to the
top of the file (maybe they should be moved to the header file).
3. changed a lot of the \n in the cout strings to cout << endl
there are some more to change but you can finish that yourself
4. I have changed a lot of the do .. while loops to while loops
(some still remain to be changed - particularly in the cashier) function.
5. You were addressing the arrays incorrectly in the addBook function - i've made some corrections there.
6. The DisplayTheArray function was never going to work - so I have commented it out - we can do that later.
7. The arrays are global - so there is no need to pass them around as function parameters (such as in the searchList function) - so they have been taken out.
8. Some functions are setup to return a value for example the bookInfo function - but they don't need to - I've changed one to void return - you can change the rest if you want.
//This program is to display the main menu screen
#include <iostream>
#include "mainmenu.h"
#include <iomanip>
#include <limits>
usingnamespace std;
constint MAX_ENTRIES =20;
constint TITLE_LENGTH =51;
constint ISBN_LENGTH =14;
constint AUTHOR_LENGTH =31;
constint PUB_LENGTH =31;
constint DATE_LENGTH = 11;
char bookTitle[MAX_ENTRIES][TITLE_LENGTH]={0};
char isbn[MAX_ENTRIES][ISBN_LENGTH]={0};
char author[MAX_ENTRIES][AUTHOR_LENGTH] = {0};
char publisher[MAX_ENTRIES][PUB_LENGTH]= {0};
char dateAdded[MAX_ENTRIES][DATE_LENGTH];
int qtyOnHand[MAX_ENTRIES];
double wholesale[MAX_ENTRIES];
double retail[MAX_ENTRIES];
/*Function prototype - probably should be moved to header file */
int searchList();
int cashier();
void invMenu(); /*changed to void return*/
int reports();
void addBook(); /*the arrays are global so no need to pass them around*/
void lookUpBook();
void editBook();
void deleteBook();
//void DisplayTheArray ( int [][]); //To be completed later
int main()
{
int choice; //Menu choice
while (true)
{
//Display the menu and get a choice
cout << endl;
cout << "Serendipity Booksellers" << endl;
cout << "Main Menu" << endl;
cout << " " << endl;
cout << "1. Cashier Module" << endl;
cout << "2. Inventory Database Module" << endl;
cout << "3. Report Module" << endl;
cout << "4. Exit" << endl;
cout << " " << endl;
cout << "Enter your choice: " << endl;
cin >> choice;
switch (choice)
{
case 1: cashier();
break;
case 2: invMenu();
break;
case 3: reports();
break;
case 4: cout << "You selected item 4." << endl;
return 0;
default:
cout << "Please choose an option from the list" << endl;
continue;
}
}
}
//This function is to display the cashier screen
int cashier()
{
//Defining variables to be requested from user
char date[8];
int quantity;
char ISBN;
char title;
float price;
float subtotal; //Defining variables to be used to show information to user
float tax;
float total;
char again; //To hold Y or N input
do
{
//Getting variables defined above from user
cin >> setw(8) >> date;
cin >> quantity;
cin >> ISBN;
cin >> title;
cin >> price;
//Calculate the total amount
subtotal = quantity * price;
tax = subtotal * 0.06;
total = subtotal + tax;
cout << "Serendipity Booksellers\n";
cout << "Date: \n";
cout << "Qty ISBN Title Price Total \n";
cout << "_____________________________________________ \n";
cout << setprecision(2) << fixed;
cout << "Subtotal: " << setw(6) << subtotal << endl;
cout << "Tax: " << setw(6) << tax << endl;
cout << "Total: " << setw(6) << total << endl;
cout << "Thank You for Shopping at Serendipity! \n";
//Does the user want to process another transaction?
cout << "Do you want to process another transaction? (Y/N) ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}
//This function is to display the inventory screen
void invMenu()
{
int choice; //Menu choice
while(true)
{
//Display the menu and get a choice
cout << endl;
cout << "Serendipity Booksellers" << endl;
cout << "Inventory Database" << endl;
cout << "1. Look Up a Book" << endl;
cout << "2. Add a Book" << endl;
cout << "3. Edit a Book's Record" << endl;
cout << "4. Delete a Book" << endl;
cout << "5. Return to the Main Menu" << endl;
cout << "Enter your choice:" << endl;
cin >> choice;
switch (choice)
{
/* Changed case values from '1' etc to integer !*/
case 1: lookUpBook();
break;
case 2: addBook(/*bookTitle*/);
break;
case 3: editBook();
break;
case 4: deleteBook();
break;
case 5: cout << "You selected item 5" << endl;
return ;
//break;
default:
cout << "Please enter a number in the range 1-5" << endl;
continue;
}
}
}
//Add stub functions for inventory database
void lookUpBook()
{
cout << "You selected Look Up Book." << endl;
}
void addBook()
{
//char size = 51; //Now redundant ??
//Search addbook array for null terminator
int bookResult = searchList(); /* don't need parameters - the arrays are global */
//If searchList returned -1, then array was full
if (bookResult == -1)
cout << "No more books may be added to the inventory." << endl;
else
{
//Otherwise results contain an empty row
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Please enter the Book Title" <<endl;
cin.getline(&bookTitle[bookResult][0],TITLE_LENGTH);
cout << "Please enter the ISBN number" << endl;
cin.getline(&isbn[bookResult][0],ISBN_LENGTH);
cout << "Please enter the Author's name" << endl;
cin.getline (&author[bookResult][0],AUTHOR_LENGTH);
cout << "Please enter the Publisher's name" << endl;
cin.getline(&publisher[bookResult][0],PUB_LENGTH);
cout << "Please enter the date the book is added to the";
cout << "inventory " << endl;
cin.getline(&dateAdded[bookResult][0],DATE_LENGTH);
cout << "Please enter the quanity of the book " << endl;
cin >> qtyOnHand[bookResult];
cout << "Please enter the wholesale price of the book " << endl;
cin >> wholesale[bookResult];
cout << "Please enter the retail price of the book " << endl;
cin >> retail[bookResult];
}
}