Creating new "dynamic" objects? - c++

What is the best way of creating dynamic (not sure if this is the correct word) objects? For example, if I run the following:
Person man[10];
cout << "MENU" << endl;
cout << "1. Add a person to the list" << endl;
cout << "2. Delete a person from the list" << endl;
cout << "3. Change a person's information'" << endl;
cout << "4. Locate a person by ID number" << endl;
cout << "5. Locate a person by last name" << endl;
cout << "6. Print the list on the screen" << endl;
cout << "7. Load the list from a file" << endl;
cout << "8. Save the list to a file" << endl;
cout << "9. Exit the program" << endl;
cin >> a;
if (a == 1) {
if (i <= 10) {
Person man[i];
cout << "Please enter your last name: " ;
cin >> last;
man[i].setLastName(last);
i++;
cout << man[i].getLastName();
}
}
When I run this, I am allowed to enter my last name, but when I press ENTER the program stops running. What is the reason for this and is there a better way to create these objects "profiles"?
Thank you and I'm sorry if this is a stupid question.

The reason is your entire program only take one input cin >> a; and then check if its equal to 1. After the block the program has nothing left to do. So your program terminated.
If you want to edit all first name and last name of your 10 Person obj, you'd better create a loop to do that. For loop, you can google for / while.
Heres a example:
int i;
while(cin >> i)
{
if(i == 9)
return;
else if[....]
}

When you say dynamic, object allocation is via new operator. In your code, the array is already declared with 10 elements(static allocation). Hence in you code you are not performing dynamic allocation.
For dynamic allocation,add a function which can return you a new Person object. In this function create a object using new operator and return this object.
This way you add new objects dynamically.
Refer to new operator for more details on dynamic allocation.

Related

My program keeps looping in the first do...while loop even when condition isn't met

I started learning C++ 3 days ago, and after some experimenting with loops and vector I decided to do something actually useful with it: an Account Manager.
The point is, I'm using a do...while loop, for the 1rst action in my program (which is adding a new website), however past this point, the loop won't end even when the condition isn't met any more.
I tried to debug it for a good 30 minutes and found nothing odd.
Here's the code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
/*Introduction
//Ask whether the user(me) wants to open an account already created, add a new one, or remove an existing one
To show credentials a master password is required
I need something that can:
1. Find the place where credentials are supposed to be filled
2. Enter them efficiently
3. Bonus : Submit the data on the website and automatically connect*/
int userAction; // Variable de sélection de la première action
string siteNameVar("site"), urlVar("url"), userNameVar("username"), passwordVar("pass") ;
char sureVerification;
vector<string> siteName(0); // Vectors containing respectively : "The sites names"
vector<string> url(0); // Vectors containing respectively : "The sites urls"
vector<string> userName(0); // Vectors containing respectively : "The usernames"
vector<string> password(0); // Vectors containing respectively : "The passwords"
cout << "What will you do?" << endl;
cout << "1. Add a website account" << endl
<< "2. Connect to an existing account" << endl
<< "3. Delete an account"<< endl;
cin >> userAction; // This is where the user enter his choice
switch (userAction){
case 1: // Add a new element in the vectors
do{
//Site Name
do{
cout << "Enter the site's name (or how you want to call it)" << endl;
cin >> siteNameVar;
cout << "Are you sure? 1 = yes | Anything else = no" << endl;
cin >> sureVerification;
}
while (sureVerification != 1);
//Site's Url
do{
cout << "Enter the site's login page url" << endl;
cin >> urlVar;
cout << "Are you sure? 1 = yes | Anything else = no" << endl;
cin >> sureVerification;
}
while(sureVerification != 1);
url.push_back(urlVar);
// Username
do{
cout << "Enter your account's username" << endl;
cin >> userNameVar;
cout << "Are you sure? 1 = yes | Anything else = no" << endl;
cin >> sureVerification;
}
while(sureVerification != 1);
userName.push_back(userNameVar);
// Password
do{
cout << "Enter your account's password" << endl;
cin >> passwordVar;
cout << "Are you sure? 1 = yes | Anything else = no" << endl;
cin >> sureVerification;
}
while(sureVerification != 1);
password.push_back(passwordVar);
//Display Everything
cout << "So the site's name is :" << siteName.back() << endl
<< "The login page url is :" << url.back() << endl
<< "Your account's username is :" << userName.back() << endl
<< "And your password is :" << password.back() << endl;
//Last verification
cout << "Is everything alright? 1 = yes | Anything else = no" << endl;
cin >> sureVerification;
}
while(sureVerification != 1);
cin.get();
break;
case 2: // Connect to an existing account
cout << "display map element names" << endl;
break;
case 3: // Delete an account
cout << "display map element names2" <<endl;
break;
} // End of the choice sequence
cin.get();
return 0;
}
You should try cleaning the input buffer. Use cin.clear() and cin.ignore() before reading the user's input (eg. before cin >> sureVerification)
(Posted on behalf of the question author).
Wow, after comparing an earlier version of my code to the code I posted, and substituting a piece of the old code to the new one (which "oddly" worked), I realized that the problem was all due to the fact that the value-type of sureVerification (read code to understand) was char and in the verification expression I had wrote the 1 (which was equivalent of "Yes" as an int.
Problem solved!

A function in my code doesn't seem to be running, can anyone tell why?

I'm building a fairly simple contact book program to sharpen my C++ skills.
Keep in mind I didn't include all my code because this post would then be massive.
The problem I'm facing is that in the area of code shown below, contactCreator() is not actually running when it is reached in the if statement.
int mainInput;
ofstream initialStream("contacts.txt", ofstream::app);
initialStream.close();
while(mainInput != -1){
system("cls");
logoHeader();
cout << endl;
cout << "--- MAIN MENU -----------------" << endl;
cout << "[0] Create New Contact" << endl;
cout << "[1] View Existing Contacts" << endl;
cout << "[2] View or Edit Data Fields" << endl;
cout << "-------------------------------" << endl;
cout << "Press ENTER without inputting" << endl;
cout << "anything to EXIT Contact Book." << endl;
cout << "-------------------------------" << endl;
cout << "Enter Selection: ";
mainInput = menuInput();
if(mainInput == 0){
//This is the function that isn't running when it's supposed to.
contactCreator();
}else if(mainInput == 1){
contactViewer();
}else if(mainInput == 2){
dataFieldViewer();
}else if(mainInput < -1 || mainInput > 2){
invalidInputError();
}
}
return 0;
Some Information about contactCreator():
It's void, so the issue is not lack of return statements according to my limited C++ knowledge.
I checked to make sure mainInput is 0, and indeed it is.
The function is declared at the top of the program before the main function. No problem there.
I checked the spelling for the function's name. All instances are correct to my knowledge.
Can anyone see if I missed something obvious? I'm pretty new to C++, so I couldn't find any syntax error myself. All of the other functions I've created in my program run perfectly.
I tried to search the internet for my problem, but I'm a bit of a loss of how to describe it simply. Why isn't contactCreator() running as expected?
Also, here are the content of the contactCreator() function if that helps. :)
string initialName;
ofstream creatorTempStream("temp.txt");
while(initialName != ""){
system("cls");
logoHeader();
cout << endl;
cout << "--- NEW CONTACT ---------------" << endl;
cout << "Enter a name for your contact." << endl;
cout << "-------------------------------" << endl;
cout << "Press ENTER without inputting" << endl;
cout << "anything to go back." << endl;
cout << "-------------------------------" << endl;
cout << "Name: ";
getline(cin, initialName);
}
Let me know if I'm missing any relevant and important information and I'll update the post. Thanks!
If menuInput() returns the right value, the problem is most likely here (unless there is other code before the while loop):
string initialName;
ofstream creatorTempStream("temp.txt");
while(initialName != ""){
}
initialName is empty at the start of the while loop.
Did you try stepping through with a debugger? In your function contactCreator(), you are checking for initialName != "" without initializing it. The chances are that the function is running without you noticing it.

Converting C to C++ and Dynamic Memory Allocation

So I have recently been tasked with converting a program I wrote in C to C++ for an assignment in an intro to programming course. The program was a basic database program where the user would create a grade book with student IDs, text names, course IDs, text names, and grades. The user would be able to interact with the menu and perform a number of operations. The most important thing was that the program could reallocate more memory when needed and it would do this automatically. So now, I'm trying to convert this program to C++.
We began discussing C++ about two and a half weeks ago in class so I am fairly new to the language. I have given a snippet for the program and what I have done so y'all can better understand my issue. I've included the class for Course and only two functions (the first adds course IDs and text name and the second prints a full list of the courses). I want the bound to start at 25, and if the user wants to put in more courses past this bound, the program will allocate more memory and copy the old entries into the new space. I'm not sure if I don't understand constructors still or what, but whenever the user inputs the 26th course it doesn't get saved. And if I try to print the courses when this happens, I get a segmentation fault.
If anyone can spot what I did wrong I would greatly appreciate it. If there's anything I didn't make clear, let me know and I'll reply as soon as I can. Thank y'all for taking the time to look at my program.
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
using namespace std;
const int MAX_COURSES=25;
//Class
class Course
{
//Two private member variables
private:
string courseText;
int courseID;
public:
//Constructor
Course(void);
//Member functions
static void addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
static void printCourses(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
};
//Class implementation
//Constructor
Course::Course(void)
{
//Just providing initial value to the two object variables
courseText;
courseID=-1;
}
//This function isn't a part of any class and will print the grade book menu.
void printMenu()
{
cout << endl;
cout << "GRADE BOOK MENU" << endl;
cout << "1. Add a new course" << endl;
cout << "2. Add a new student" << endl;
cout << "3. Add a student to a course" << endl;
cout << "4. Add grades for a student in a course" << endl;
cout << "5. Print a list of all grades for a student in a course" << endl;
cout << "6. Print a list of all students in a course" << endl;
cout << "7. Compute the average for a student in a course" << endl;
cout << "8. Print a list of all courses" << endl;
cout << "9. Print a list of all students" << endl;
cout << "10. Compute the average for a course" << endl;
cout << "11. Store grade book (to a disk file" << endl;
cout << "12. Load grade book (from a disk file" << endl;
cout << "13. Quit the program" << endl;
cout << "14. Check individual student 2D grade matrix" << endl;
cout << endl;
}
//This method function will add a course to the course list
void Course::addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter)
{
int userEnteredCourseID=0;
Course* pointerCourses=NULL;
pointerCourses = courses;
do
{
cout << endl;
cout << "Please enter a course ID number using only integers." << endl;
cout << "There is a limit of only 25 courses allowed in the grade book." << endl;
cout << "To exit to grade book menu at any time, enter a negative integer or 0." << endl;
cout << "A message will be returned to you and no course IDs will be added." << endl;
cin >> userEnteredCourseID;
//Checking for a valid integer input.
while(cin.fail())
{
cout << "Error! User entered something other than an integer." << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Try entering a valid integer input this time..." << endl;
cin >> userEnteredCourseID;
}
cout << "You have entered the integer " << userEnteredCourseID << endl;
/*Checking if they entered a negative integer value.*/
if(userEnteredCourseID<=0)
{
cout << endl;
cout << "You have entered a negative integer or 0. Nothing has been added" << endl;
cout << "to the course list and you will be returned to the menu." << endl;
}
/*A valid integer was entered.*/
else
{
/*Now need to check if the course has been entered before. Should be noted, only
course ID numbers will be checked, not text names. Two course IDs could exist for
the same course; these ID numbers could represent different times for the same
course.*/
int j;
for(j=0; j<MAX_COURSES+(*timesReallocatedCoursesCounter); j++)
{
/*Checks if user has entered that course ID before.*/
if(courses[j].courseID==userEnteredCourseID)
{
cout << "You've already entered that course ID!" << endl;
userEnteredCourseID=0;
break;
}
/*If the current element doesn't equal the course ID entered, keep traversing the array.*/
else if(courses[j].courseID!=userEnteredCourseID && j<=((MAX_COURSES + (*timesReallocatedCoursesCounter))-2))
{
continue;
}
/*Entire loop was traversed and there weren't any duplicate course IDs, so a new course will be added to array.*/
else
{
//Since the previous bounds for courses used to be 25, we'll leave that part of the code in.
//However, since we now want to allow for infinite inputs, if the user reaches 25
//courses, the program will reallocate memory and allow for more courses to be entered.
//Only memory space for one course will be allocated each time so space isn't wasted.
if(*courseCounter==(MAX_COURSES + (*timesReallocatedCoursesCounter)))
{
courses = new Course[MAX_COURSES + *timesReallocatedCoursesCounter + 1];
for(int m=0; m < MAX_COURSES + *timesReallocatedCoursesCounter; m++)
{
courses[m] = pointerCourses[m];
}
delete[] pointerCourses;
*timesReallocatedCoursesCounter+=1;
courses[*courseCounter].courseID=userEnteredCourseID;
cout << "What would you like the new course to be called?" << endl;
cin.ignore();
getline(cin, courses[*courseCounter].courseText);
cout << "Course " << userEnteredCourseID << " has successfully been registered with the name " << courses[*courseCounter].courseText << endl;
*courseCounter+=1;
cout << "Press enter to continue." << endl;
cin.ignore();
}
else
{
courses[*courseCounter].courseID=userEnteredCourseID;
cout << "What would you like the new course to be called?" << endl;
cin.ignore();
getline(cin, courses[*courseCounter].courseText);
cout << "Course " << userEnteredCourseID << " has successfully been registered with the name " << courses[*courseCounter].courseText << endl;
*courseCounter+=1;
cout << "Press enter to continue." << endl;
cin.ignore();
}
}
}
}
}while(userEnteredCourseID>0);
}
//This method function prints the courses that have been successfully entered by the user.
void Course::printCourses(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter)
{
if(*courseCounter==0)
{
cout << endl;
cout << "You haven't entered any course IDs successfully yet!" << endl;
}
else
{
int i;
cout << endl;
cout << *courseCounter << " course(s) successfully entered so far." << endl;
cout << "The gradebook started with allowing only 25 courses to be entered." << endl;
cout << "Due to the amount of courses entered by the user, memory has been reallocated" << endl;
cout << *timesReallocatedCoursesCounter << " time(s) (in increments of 1) so entries could be made." << endl;
cout << "This means, a maximum of " << MAX_COURSES+*timesReallocatedCoursesCounter << " courses can be entered before reallocation is needed." << endl;
cout << "The list of the courses entered so far are:" << endl;
for(i=0;i<*courseCounter;i++)
{
cout << endl;
cout << courses[i].courseID << ": " << courses[i].courseText;
}
cout << endl;
}
}
//Main program file.
int main(void)
{
Course *courses;
courses = new Course [MAX_COURSES];
int userInput;
int courseCounter = 0;
int timesReallocatedCoursesCounter = 0;
do
{
/*Function that will re-print grade book menu.*/
printMenu();
cout << "What would you like to do with the menu?" << endl;
cin >> userInput;
while(cin.fail())
{
cout << "Error! User entered something other than an integer." << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Try entering a valid integer input this time..." << endl;
cin >> userInput;
}
cout << "You have entered the integer " << userInput << endl;
if(userInput==1)
{
cout << "You want to add a new course." << endl;
Course::addCourse(courses, &courseCounter, &timesReallocatedCoursesCounter);
}
else if(userInput==2)
{
cout << "You want to add a new student." << endl;
}
else if(userInput==3)
{
cout << "You want to add a student to a course." << endl;
}
else if(userInput==4)
{
cout << "You want to add a grade for a student in a course." << endl;
}
else if(userInput==5)
{
cout << "You want to print the grades for a student in a course." << endl;
}
else if(userInput==6)
{
cout << "You want to print a list of students in a course." << endl;
}
else if(userInput==7)
{
cout << "You want to compute the average for a student in a course." << endl;
}
else if(userInput==8)
{
cout << "You want to print a list of all courses." << endl;
Course::printCourses(courses, &courseCounter, &timesReallocatedCoursesCounter);
}
else if(userInput==9)
{
cout << "You want to print a list of all students." << endl;
}
else if(userInput==10)
{
cout << "You want to compute the average for a course." << endl;
}
else if(userInput==11)
{
cout << "You want to store the grade book you've been working on to a text file." << endl;
}
else if(userInput==12)
{
cout << "You want to load a grade book you've worked on previously from a text file." << endl;
}
else if(userInput==13)
{
cout << "You want to quit the program." << endl;
cout << "Goodbye, and thank you for using this program!" << endl;
}
else if(userInput==14)
{
cout << "An optional menu function that prints an individual student's 2D array." << endl;
cout << "This array contains all the course IDs for which the student is enrolled on the top row." << endl;
cout << "The rows below the course IDs correspond to grades made by the student in each course." << endl;
}
else
{
cout << "User entered an integer value that doesn't correspond to any menu option." << endl;
cout << "Nothing will happen." << endl;
}
}while(userInput!=13);
delete[] courses;
return 0;
}
but whenever the user inputs the 26th
Maybe because of this:
const int MAX_COURSES=25;
//...
Course *courses;
courses = new Course [MAX_COURSES]
You allocated room for 25 students, not 26. However, this issue would have occurred if you just used arrays:
Course courses[MAX_COURSES];
With an array you may have crashed, but the issue is the same -- a memory overwrite. So either decide -- limit the user to 25 students, or allow any number of students. If it's the latter, then you need to use a dynamic array.
The most important thing was that the program could reallocate more memory when needed and it would do this automatically. So now, I'm trying to convert this program to C++.
If you do with the dynamic array, it would have been advantageous to learn to use std::vector instead of using new[]/delete[]. That is the way dynamic arrays are done using C++. If you instead stick with new[]/delete[] to attempt to resize, all I can tell you is "good luck". I can almost bet you will come back with more issues if you choose the new[]/delete[] path.
The way the vector approach would look is something like this:
#include <vector>
//...
typedef std::vector<Course> CourseVector;
//...
void addCourse(CourseVector& v)
{
Course tempCourse;
// gather all the user information in tempCourse
//...
// now add the course to the array
v.push_back(tempCourse);
}
It took a single line of code to add a course to the vector. A vector is nothing more than a wrapper around a dynamic array. It basically does new[]/delete[] but with one huge advantage - it uses these operations correctly. You never need to get your hands dirty doing this work and making mistakes. The vector knows when to allocate, when to destroy, etc. All you need to do is call the functions to resize(), push_back(), etc.
I think your issue is that you are passing in the courses pointer by value. That is, a new copy of courses is created on the call stack, and you are operating on that copy. The copy is lost after addCourse() is executed. So for the first 25 courses that you add, your program works as normal since the copy of the courses pointer points to the same memory block as the "original". When you try to dynamically increase the size of courses by allocating a new block of larger memory, you are not doing anything to the original pointer in main(). This is why I think you are segfaulting when you print out the list.
A possible solution is to have addCourse() return the larger array, set it to courses in main(), and then deallocate the old array.
The prototype for the new addCourse() function would look like this:
static Course* addCourse(Course* courses, int *courseCounter, int *timesReallocatedCoursesCounter);
Inside the function allocate the larger array using a new Course pointer, and copy the values one by one into the new array. Then, return the new array.
and to call it, use a statement like:
Course* newCourses = addCourse(...);
delete [] courses;
courses = newCourses;

My list objects are being destroyed

list<Book> *books = new list<Book>;
list<Book>::iterator pos;
void Administrator::addBook()
{
Book *newBook = new Book();
cout << "Would you like to enter a book?" << endl;
cin >> userInput;
cout << endl;
if (userInput == "yes")
{
cout << "What is the title of the book you want to enter?" << endl;
cin >> title;
cout << "What is the author of the book you want to enter?" << endl;
cin >> author;
cout << "What is the ISBN of the book you want to enter?" << endl;
cin >> ISBN;
cout << endl;
newBook->setTitle(title);
newBook->setAuthor(author);
newBook->setISBN(ISBN);
newBook->setAvailability(true);
books->push_back(*newBook);
}
}
*****************
I really need help with this, i have received a few answers today but none have helped me with this problem. This is my admin class. It creates books on the heap and stores them in an stl::list
void Guest::searchBook(Book* search)
{
string searchBook;
cout << "What book would you like to search for?" << endl;
cin >> searchBook;
printBookDetails();
}
This is my Guest class, what i would like to do here is to search through the list of books i created in my Administrator class but when it goes into the function printBookDetails, my list contains no elements, im assuming they've been destroyed.
Administrator* admin1 = new Administrator("jayfitz91", 24681357);
Guest* guest1 = new Guest("guest", 0000);
void main()
{
//Everything here works fine
admin1->addBook();
admin1->addBook();
admin1->makeAvailable();
admin1->printBookDetails();
//My list is destroyed at this point and it returns nothing
guest1->printBookDetails();
My Guest class inherits the printBookDetails from my Administrator class
All of the admin functions work but as soon as it gets to guest, the elements disappear.
Is there anyway i can get around this? The help would greatly be appreciated
Thanks to #OldProgrammer, i realised i had to return the list of books from my Admin class and pass it through as a parameter to my printBookDetails method in my guest class:
//Admin class
//Now returning a list
list<Book> Administrator::addBook()
{
Book *newBook = new Book();
cout << "Would you like to enter a book?" << endl;
cin >> userInput;
cout << endl;
if (userInput == "yes")
{
cout << "What is the title of the book you want to enter?" << endl;
cin >> title;
cout << "What is the author of the book you want to enter?" << endl;
cin >> author;
cout << "What is the ISBN of the book you want to enter?" << endl;
cin >> ISBN;
cout << endl;
newBook->setTitle(title);
newBook->setAuthor(author);
newBook->setISBN(ISBN);
newBook->setAvailability(true);
books->push_back(*newBook);
}
return *books;
}
//Guest class function
void Guest::printBookList(list<Book> *tempList)
{
pos = tempList->begin();
for (pos = tempList->begin(); pos != tempList->end(); ++pos)
{
cout << pos->getTitle() << "\n"
<< pos->getAuthor() << "\n"
<< pos->getISBN() << "\n"
<< pos->getAvailability() << "\n"
<< "******************************" << endl;
}
}
//Main class function
//Create a temporary variable for the list
list<Book> tempList;
//pass it through to the method
guest1->printBookList(&tempList);
First off, you don't have to dynamically create your list object.
list<Book> books = new list<Book>();
You do this because
you have less responsibility: you don't have to release the resources contained by books. It will automatically be released.
list is a stl container, which means it automatically handles dynamic allocations.
This is different if you use an dynamically allocated array...
I think your list is "gone" is because Guest and Administrator has two entirely different list.
To solve this issue, you should grant access to the book list that Administrator has to your Guest.
Or extract out the book list and store it in another class that allow access to the list to both Administrator and Guest.

getting this function to loop properly

I am making a function to give the time taken to travel from Chicago to a certain city. I am trying to make it loop so that when the user chooses the city, it gives the time taken and loops back up to ask the main question and let the user choose another city. I am also including an option where they can exit the loop. What I have so far is this:
main()
{
TripInfo trip;
int choice;
do
{
cout << "You are in Chicago. Where would you like to drive?\n"
<< "Enter number of city\n" << "1. New York City\n" << "2. Boston\n"
<< "3. Philadelphia\n" << "4. Toronto\n" << "5. Washington D.C.\n"
<< "6. Miami\n" << "7. Indianapolis\n" << "8. Los Angeles\n"
<< "9. San Fransisco\n" << "10. Phoenix\n" << "11. EXIT" << endl;
cin >> choice;
if(choice = 11)
{
cout << "Program terminated." << endl;
break;
}
trip.setDistance(choice);
cout << "The distance from Chicago to " << trip.getDestination() << " is "
<< trip.getDistance() << endl;
trip.setRate();
cout << "The speed you will be travelling at from Chicago to "
<< trip.getDestination() << " is " << trip.getRate() << endl;
trip.calculateTime();
cout << "The time it will take to travel from Chicago to "
<< trip.getDestination() << " at " << trip.getRate()
<< " miles per hour will be:\n " << trip.getTime() << " hours."
<< endl;
}
}
The problem is in the output. Even though there is a condition for the if statement and if choice is not 11, the function still prints "Program terminated.". How do I fix this so that if choice = 11, the program terminates, and if choice is not 11, it continues and loops through the various functions again and again until choice is chosen to be 11?
You want choice == 11. A single = sign causes 11 to be assigned to choice (and that assignment evaluates to true).
You need to use == to compare for equality; = is assignment, returning the value assigned, and nonzero is interpreted as true.
A convention I've seen to try to prevent this issue is to put the constant on the left. The following block of code will produce a compiler error:
if(11 = choice)
{
cout << "Program terminated." << endl;
break;
}
if(choice = 11)
means you assign choice a value of 11, and test for if value is non-zero, which is true. It should be
if(choice == 11)
The correct format is
if(choice == 11) {
--- }
= is used for assignment and == is used for checking the equality.
Also you have to give a whilecondition at the end of do statement for checking the condition to enter in the loop again.
if (choice = 13) {......}
the expression is true ever, assignment expression value is var's value, above is choice, the assignment expression is 13, 13 is true.
you can write 13 = choice to protect error by compiler, but i suggest you write choice == 13 ways, because this ways will understand well.