C++ 2d Array Class Function Call Help - c++

I hope this question takes a simple fix, and I am just missing something very small.
I am in my second semester of C++ in college, and we are just getting into OOP. This is my first OOP program, and it is causing me a little problem. Here are the errors I am getting:
Member function must be called or its address taken in function displayGrid(int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Warning: Parameter 'grid' is never used in function displayGrid(int,Cell ( *)[20])
Here is all of my code. I am aware It is much more code than necessary, sorry if it makes it more difficult. I was worried that I might accidentally delete something.
const int MAX=20;
//Struct Cell holds player and their symbol.
class Cell
{
private:
int Player;
char Symbol;
public:
Cell(void);
void setPlayer(int);
void setSymbol(char);
int getPlayer(void);
char getSymbol(void);
};
Cell::Cell(void)
{
Symbol ='-';
}
void Cell::setPlayer(int player_num)
{
Player = player_num;
}
void Cell::setSymbol(char rps)
{
Symbol = rps;
}
int Cell::getPlayer(void)
{
return Player;
}
char Cell::getSymbol(void)
{
return Symbol;
}
void Turn(int, int, Cell[MAX][MAX]);
void displayGrid(int, Cell[MAX][MAX]);
void main(void)
{
int size;
cout << "How big would you like the grid to be: ";
cin >> size;
//Checks to see valid grid size
while(size>MAX || size<3)
{
cout << "Grid size must between 20 and 3." << endl;
cout << "Please re-enter the grid size: ";
cin >> size;
}
int cnt=1;
int full;
Cell grid[MAX][MAX];
//I use full to detect when the game is over by squaring size.
full = size*size;
cout << "Starting a new game." << endl;
//Exits loop when cnt reaches full.
while(cnt<full+1)
{
displayGrid(size, grid); //calls function to display grid
if(cnt%2==0) //if cnt is even then it's 2nd players turn
cout << "Player 2's turn." << endl;
else
cout << "Player 1's turn" << endl;
Turn(size, cnt, grid); //calls Turn do each players turn
cnt++;
}
cout << endl;
cout << "Board is full... Game Over" << endl;
}
void displayGrid(int size, Cell grid[MAX][MAX])
{
cout << endl;
cout << " ";
for(int x=1; x<size+1; x++) // prints first row
cout << setw(3) << x; // of numbers.
cout << endl;
//Nested-For prints the grid.
for(int i=1; i<size+1; i++)
{
cout << setw(2) << i;
for(int c=1; c<size+1; c++)
{
cout << setw(3) << grid[i][c].getSymbol;
}
cout << endl;
}
cout << endl;
}
void Turn(int size, int cnt, Cell grid[MAX][MAX])
{
char temp;
char choice;
int row=0;
int column=0;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
//puts what is in the current cell in "temp"
temp = grid[row][column].getSymbol;
//Checks to see if temp is occupied or not
while(temp!='-')
{
cout << "Cell space is Occupied..." << endl;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
temp = grid[row][column].getSymbol; //exits loop when finally correct
}
if(cnt%2==0) //if cnt is even then its player 2's turn
{
cout << "Enter your Symbol R, P, or S (Capitals): ";
cin >> choice;
grid[row][column].setPlayer(1);
in >> choice;
}
//officially sets choice to grid cell
grid[row][column].setSymbol(choice);
}
else //if cnt is odd then its player 1's turn
{
cout << "Enter your Symbol r, p, or s (Lower-Case): ";
cin >> choice;
grid[row][column].setPlayer(2);
//checks for valid input by user1
while(choice!= 'r' && choice!='p' && choice!='s')
{
cout << "Invalid Symbol... Please Re-Enter: ";
cin >> choice;
}
//officially sets choice to grid cell.
grid[row][column].setSymbol(choice);
}
cout << endl;
}
Thanks alot for your help!

The following line:
cout << setw(3) << grid[i][c].getSymbol;
Doesn't call the function. Write this instead:
cout << setw(3) << grid[i][c].getSymbol();
Likewise for the other error messages.
The warning is generated because the erroneous line is the only time displayGrid uses the grid parameter.

You forgot the function parens:
cout << setw(3) << grid[i][c].getSymbol;
should be:
cout << setw(3) << grid[i][c].getSymbol();

Related

Output does not include all input for my array

I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}

Arrays Lose Value Upon Return (Inventory/Menu Program) C++

So for the most part I understand what I did wrong, the issue is I don't know how to fix it.
Goal: This is a store management system that must include a menu and inventory management functions that can be manipulated. To do this I used arrays to add the store's items, their descriptions, and their quantities. All the arrays are partially filled to the third element and have a max value of ten elements.
Issue: When the program is run the first time it works and the user can see their inventory, description and quantity. However when they exit to the menu and come BACK to inventory, everything past the third element is cleared. This is due to the declarations initializing the arrays past the third element to 0. How do I fix this to guarantee the user has their inventory saved and can view it upon return?
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
//declarations
int mainMenu(); //done
void inventoryMgmt();
void addInv(); //working on
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void customerReciept(); //done
void calculatePrice(); //done
void exit(); //done
const double massTax = 0.0625;
//main
int main() {
int choice;
bool repeat = true;
while (repeat = true) {
choice = mainMenu();
switch (choice) {
case 1:
customerReciept();
break;
case 2:
inventoryMgmt();
break;
//case 3:
//itemSearcher();
//break;
case 4:
exit();
repeat = false;
break;
}
}
return 0;
}
//main menu function ***done
int mainMenu() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Main Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Customer Reciept" << endl;
cout << "\t\t\t\t\t\t 2. Inventory Management" << endl;
cout << "\t\t\t\t\t\t 3. Item Search" << endl;
cout << "\t\t\t\t\t\t 4. Exit" << endl << endl;
int choice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> choice;
while (choice < 1 || choice > 4) {
cout << "\t\t\t\t\t Incorrect Selection Please Select Again: ";
cin >> choice;
}
return choice;
}
//customer reciept function **done
void customerReciept() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Receipt Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Calculate Receipt" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
int recieptChoice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> recieptChoice;
while (recieptChoice < 1 || recieptChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> recieptChoice;
}
if (recieptChoice == 1) {
calculatePrice();
}
}
void calculatePrice() {
double cost;
double taxAmount;
int numOfItems;
double finalCost = 0;
char tax;
int i;
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "How many items were purchased?: ";
cin >> numOfItems;
for (i = 0; i < numOfItems; i++) {
cout << "What did item " << i + 1 << " cost? $";
cin >> cost;
cout << "Is this item taxable? (y/n):";
cin >> tax;
if (tax == 'y' || tax == 'Y') {
taxAmount = (cost * massTax);
cost = taxAmount + cost;
finalCost = cost + finalCost;
}
else {
finalCost = cost + finalCost;
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "This customer's total is $" << finalCost << endl;
}
void inventoryMgmt() {
int invChoice;
cout << "\n\n\t\t\t\t\t Welcome to Inventory Management " << endl;
cout << "\t\t\t\t ______________________________________________ \n\n";
cout << "\t\t\t\t\t Inventory Settings: " << endl;
cout << "\t\t\t\t\t\t 1. Add/View & Edit/Delete Inventory" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> invChoice;
cout << endl << endl;
while (invChoice < 1 || invChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> invChoice;
}
if (invChoice == 1) {
addInv();
}
if (invChoice == 2) {
//edit/delete();
}
}
void addInv() {
//so when this is called, everything is initialized to 0 which makes it wipe the memory
//when the user comes back to it from the menu.
const int description = 20; //this allows a short description for each item
const int counter = 10; //slots of inventory allowed
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "Hot Drinks", "Cold Drinks", "Books"};
string descriptionArray[description] = { "Coffee, Tea etc", "Water, juice, etc", "Texts, notebook, etc"};
char addChoice;
int destination;
cout << "\t\t\t\t\t\t 1. Add/View" << endl;
cout << "\t\t\t\t\t\t 2. Edit/Delete" << endl;
cout << "\t\t\t\t\t\t 3. Exit to Main" << endl;
cout << "\t\t\t\t\t\t Where would you like to go?: " << endl;
cin >> destination;
while (destination < 1 || destination > 3) {
cout << "Invalid Selection, Please Select Again: ";
cin >> destination;
}
if (destination == 1) {
cout << "Would you like to add an item? (y/n): ";
cin >> addChoice;
int i = 3; //these two are initialized to three to ensure that the store
int ii = 3; //will always have hot drinks, cold drinks and books as options
while (addChoice == 'y' && i < counter) {
cout << "What would you like to add?: ";
cin >> itemArray[i];
cout << "You have added \"" << itemArray[i] << "\" to the inventory\n";
cout << "Please Provide a Brief Description: ";
cin.ignore();
getline(cin, descriptionArray[ii]);
cout << "You've described \"" << itemArray[i] << "\" as \"" << descriptionArray[i] << "\"" << endl;
cout << "What is the quantity of " << itemArray[i] << " in stock?";
cin >> quantity[i];
cout << "Would you like to add another item?";
cin >> addChoice;
i++;
ii++;
if (i > counter) {
cout << "**INVENTORY LIMIT REACHED*** ";
}
}
invView(itemArray, 10, descriptionArray, 10, quantity, 10); //working on this. //so use this for view, edit, and delete.
}
}
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) { //add quantity
int i = 0;
int ii = 0;
int iii = 0;
cout << "Your inventory consists of: ";
while (i < sizeofArray && x[i] != "" && ii < secondArray && y[i] != "" && iii < thirdArray) {
cout << x[i] << " - " << y[i] << " | Quantity: " << z[i] << endl;
i++;
ii++;
}
}
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) {
cout << "Which item would you like to edit?";
}
void exit() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t Thank you for using the Massasoit Store Management System" << endl;
exit(1);
}
I included the entire code in case it was needed. The issues are centered around the inventoryMgmt() and addInv() functions.
Thanks in advance for any help!
In theaddInv() all the arrays are local. Once that function is done executing, all local variables are freed up thus resulting in your deletion. Try place them outside your addInv() function:
int main(){
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "..."};
string descriptionArray[description] = { "..."};
void addInv() {...}
}

Cant create array of objects in c++

#include <iostream>
using namespace std;
class Bank
{
private:
char account_holder[50];
int accnum;
int balance;
int dep_amount;
int with_amount;
public:
void getdata();
void putdata();
void deposit();
void withdraw();
};
void Bank::getdata()
{
cout << "Enter the account holders name : " << endl;
cin >> account_holder;
cout << "Enter the account number : " << endl;
cin >> accnum;
cout << "Enter the balance in your account : " << endl;
cin >> balance;
}
void Bank::putdata()
{
cout << "The account holders name is : " << account_holder << endl;
cout << "The account number is : " << accnum << endl;
cout << "The balance in your account is : " << balance << endl;
cout << endl;
}
void Bank::deposit()
{
cout << "Enter the amount to be deposited : " << endl;
cin >> dep_amount;
balance = balance + dep_amount;
cout << "Your current balance is : " << balance << endl;
}
void Bank::withdraw()
{
cout << "Enter the amount to be withdrawn : " << endl;
cin >> with_amount;
balance = balance - with_amount;
cout << "Your current balance is : " << balance << endl;
}
int main(){
Bank ram[5];
int ch, a, n, acc;
cout << "How you account holders you want to add : " << endl;
cin >> n;
do
{
cout << "Enter 1.To insert data" << endl;
cout << "Enter 2.To display data" << endl;
cout << "Enter 3.To deposit amount" << endl;
cout << "Enter 4.To withdraw amount" << endl;
cout << "Enter your choice : " << endl;
cin >> ch;
switch (ch)
{
case 1:
for (int i = 0; i < n;i++)
ram[i].getdata();
break;
case 2:
for (int i = 0; i < n; i++)
ram[i].putdata();
break;
case 3:
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
for (int i = 0; i < n; i++)
ram[acc].deposit();
break;
case 4:
for (int i = 0; i < n; i++)
ram[i].withdraw();
break;
}
cout << "Enter 6. To Continue" << endl;
cin >> a;
} while (a == 6);
return 0;
}
I am using this code and my problem is that when I want to deposit or withdraw some amount,I want to take account number from user and then deposit/withdraw amount from that object only. How can I enter that object using account number taken from user? Please Help.
Unfortunately you have a few problems with your code and your logic. Let us address them one by one:
1- You are using a char array to keep the account holder name. If you are programming C++ you should be using std::string in almost all situations.
2- You are using unconventional names for your public methods in Bank and this is a bad habit at best.
More specifically, getdata() is a poor method name because mehtods that start with "get" should generally be reserved for methods that return a single field that belongs to the class instance. For example int getAccountNumber()
your getdata() should be fillInData() follow me?
3- You are using an array of Bank in your main in order to hold the number of accounts. While this is possible, it is far from ideal. You should strive to use std::vector when it makes sense (like here). Why is a naked array bad? because if you use an array the size of the array has to be known at compile time, which means you can not increase the number of accounts when the program is running. If you declare a big array on the stack, you may have a lot of space but you are wasting precious stack space.
4- The logic you have employed for your "input loop" is messy and hard to navigate. The design can be improved significantly to improve readability and maintainability of code. Consider the fact that you declare and read int n; but you never use it in the program.
5- Compile time errors from undeclared variables like i
6- Logically and semantically incorrect program behaviour: you iterate through a for loop of all records and withdraw/deposit in ALL records, instead of selecting the one you need.
7- No bounds checking of any kind. Asking for bad things to happen.
I am giving you a minimally adjusted code that makes sense. Note that this is still not the ideal way to accomplish this task but at least it does not have syntax and semantic errors:
int Bank::getAccountNumber()
{
return this->accnum;
}
int getIndexByAccountNumber(Bank allAccounts[], int size, int accountNumber) //returns index or -1 in case account number is not found
{
for(int i=0; i<size; ++i)
{
if (allAccounts[i].getAccountNumber()==accountNumber) return i;
}
return -1;
}
int main(){
const int NumberOfAccounts=5;
Bank ram[NumberOfAccounts];
int nextIndex=0;
int ch, a, acc;
while(true)
{
cout << "Enter 1.To insert data for a new account" << endl;
cout << "Enter 2.To display data of all existing accounts" << endl;
cout << "Enter 3.To deposit to an existing account" << endl;
cout << "Enter 4.To withdraw from an existing account" << endl;
cout << "Enter 5.To terminate program" << endl;
cout << "Enter your choice : " << endl;
cin >> ch;
if(ch==1)
{
if(nextIndex>=NumberOfAccounts)
{
cout<<"error: you have space for only "<<NumberOfAccounts<<" accounts! terminating program";
break;//breaks out of while loop
}
ram[nextIndex].getdata();//gets all fields for the account
nextIndex++;
}
else if(ch==2)
{
cout << "showing information for all accounts: " << endl;
for (int i = 0; i < nextIndex; i++) ram[i].putdata();
cout<<"\n\n";
}
else if(ch==3)
{
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
int index = getIndexByAccountNumber(ram,NumberOfAccounts,acc);
if(index==-1)
{
cout<<"the account number you entered could not be found, terminating program!\n";
break;//breaks out of while loop
}
ram[index].deposit();
}
else if(ch==4)
{
cout << "Enter the account you want to withdraw from " << endl;
cin >> acc;
int index= getIndexByAccountNumber(ram,NumberOfAccounts,acc);
if(index==-1)
{
cout<<"the account number you entered could not be found, terminating program!\n";
break;//breaks out of while loop
}
ram[index].withdraw();
}
else if(ch==5)
{
break;
}
else
{
cout<<"you entered invalid choice\n";
}
}//end of while loop
return 0;
}
cout << "Enter the account you want to deposit money into " << endl;
cin >> acc;
for (int i = 0; i < n; i++)
ram[acc].deposit();
break;
Here is your problem - wrong index variable. Try "i"
In your case 3 you use a different iterator than the rest. Is this by design or what? I am missing the purpose of using acc instead of i. This might be your problem, unless I am overlooking your purpose for using it.

Restricting string length and issues with string not being outputted

So first off here is my code so far
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Car
{
public:
void setUp(string, int, string, bool, string);
void output();
private:
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
};
void input (Car *ptr);
int main()
{
Car *ptrCar = new Car;
string reportingMark = " ";
int carNumber=0;
string kind ="business";
bool loaded= true;
string destination =" ";
Car *ptr = new Car;
input(ptr);
ptr->setUp(reportingMark, carNumber, kind, loaded, destination);
ptr->output();
}
void input (Car *ptr)
{
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
cout << "Please input your AAR reporting mark" << endl;
cin >> reportingMark;
do
{
if (reportingMark.length() <2 || reportingMark.length() >4);
{
cout << "Invalid. Please try again."<< endl;
cout << reportingMark.length();
cin >> reportingMark;
}
}while(reportingMark.length() >= 2 || reportingMark.length() <= 4);
cout<< reportingMark << endl;
cout<< "Please input your car number." << endl;
cin >> carNumber;
cout << carNumber<<endl;
cout << "What kind of car is it?" << endl;
cin.ignore();
getline(cin,kind);
cout << kind << endl;
cout <<"Is your car loaded? (1 - yes or 0 - no)" <<endl;
cin >> loaded;
cout << loaded << endl;
if(loaded == 0)
{
cout << "Do you have a destination? If so, where? If not, type NONE" << endl;
cin.ignore();
getline(cin,destination);
}else if (loaded == 1)
{
cout << "Where is your destination?" << endl;
cin.ignore();
getline(cin,destination);
cout << destination << endl;
}
}
void Car::setUp(string rMark, int cNumber, string cKind, bool cLoaded,
string dest)
{
reportingMark = rMark;
carNumber = cNumber;
kind = cKind;
loaded = cLoaded;
destination = dest;
}
void Car::output()
{
cout << "AAR Reporting Mark:" << reportingMark << endl;
cout << "Car Number:" << carNumber << endl;
cout << "Kind:" << kind << endl;
cout << "Your car is:" << loaded << endl;
cout << "Destination:" << destination << endl;
}
What I'm struggling with is specifically that my lab asks for
A string named reportingMark to contain two to four characters
Every input I enter keeps giving me the invalid option when the number of characters in the string isn't 2-4. Even when I try inputs of 2-4 characters.
My other issue is "destination" The input I give isn't outputting my input correctly, it just appears to what I have in int main which is blank space.
You have couple of errors in the do-while loop.
do
{
if (reportingMark.length() <2 || reportingMark.length() >4);
// The ; in the above line is the end of the if statment.
// The following block of code gets executed no matter what
{
cout << "Invalid. Please try again."<< endl;
cout << reportingMark.length();
cin >> reportingMark;
}
}while(reportingMark.length() >= 2 || reportingMark.length() <= 4);
The conditional in while is not right either. It should be the same as the one in the if statement.
}while(reportingMark.length() < 2 || reportingMark.length() > 4);
You can remove the duplicate code by using:
while ( true )
{
cin >> reportingMark;
// The length is used many times. Might as well use a variable.
size_t length = reportingMark.length();
if (length >= 2 && length <= 4)
{
break;
}
cout << "Invalid length. Please try again."<< endl;
cout << length << endl;
}

C++ Address Book Array and Textfile

Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}