I am making a phonebook program for c++ and am having trouble transferring my search function into my main function. When I compile it and search for the name, it crashes the program.
Search Function:
int search(string name){
for(int i=0; i<counter; i++){
if(data[i][0] == name){
return i;
}
else{
cout << "Name not found" << endl;
}
}
}
Main Function:
int main(){
bool done = false;
int choice;
string name;
string areaCode;
string number;
load_contacts("contacts.txt");
cout << "Welcome to AddressBook" << endl;
while(!done){
cout << "What would you like to do?" << endl;
cout << "1) Display all contacts" << endl;
cout << "2) Add a contact" << endl;
cout << "3) Remove a contact" << endl;
cout << "4) Search a contact" << endl;
cout << "5) Exit" << endl;
cin >> choice;
switch (choice){
case 1:
display_contacts();
break;
case 2:
add_contacts(name, areaCode, number);
cout << "Contact Added!";
cout << endl;
break;
case 3:
cout << "Name to remove: ";
cin >> name;
remove_contacts(name);
break;
case 4:
cout << "Name to search: ";
cin >> name;
search(name);
break;
case 5: cout << "Good bye." << endl;
done = true;
break;
}
}
}
There are several issues with the code you posted, mostly due to undefined variables being called.
1: For your search method, counter comes out of nowhere and is being used as a numeric limiter for the loop.
2: Also within your search method, the 2D array data is also undefined, unless it is a global variable set from the load_contacts method that isn't being shown, so currently you're searching a 2D array that doesn't exist.
3: Your "Name not found" message is in an else statement within the for loop in your method, therefore being executed every time a loop doesn't find the name. You may want to move that outside of the loop to print and then return an error number, maybe -1 to handle later.
4: Your search method is a return type of int, however in your main you are not assigning the returned value to any variable to be used, so if there is a successful search, nothing will happen.
If I'm incorrect with any of these, please tell me, but I would focus on the obvious errors first to see if they are causing the crashing.
Related
This is my first question here. I am just beginning to learn C++ and I am stuck at this exercise:
Your program should display a menu options to the user as follows:
P--Print the vector
A--Add a number
M--Display mean of the number
S--Display the smallest number
L--Display the largest number
Q--Quit
Enter your choice:
Basically, I need to do a menu for these operations. I got stuck at the part of printing the vector. I already tried to use (for auto:....) and also tried with the normal index (int i = 0...), but the contents in the vector don't appear, only the message "This is your list of numbers:". I also tried to create a function to make sure that the user was inputting an integer in the A case, but did not know how to do it :(
This is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
bool control_end = false;
do
{
cout << "Please enter your desired function within the menu: " << endl;
cout << endl;
cout << "P--Print list of numbers" << endl;
cout << "A--Add a number"<< endl;
cout << "M--Display mean of the number"<< endl;
cout << "S--Display the smallest number"<< endl;
cout << "L--Display the largest number"<< endl;
cout << "Q--Quit "<< endl;
cout << endl;
cout << "Enter your choice: ";
char letra{};
cin >> letra;
vector<int> vector{};
switch(letra)
{
case 'A':
case 'a':
{
cout << "Please enter the value (integer) to be added to vector: ";
int value_add;
cin >> value_add;
cout << endl;
vector.push_back(value_add);
//(later do it) create a function to ensure that the value is an integer
break;
}
case 'p':
case 'P':
{
cout << "This is your list of numbers: \n";
for (unsigned int i=0 ;i < vector.size(); i++)
cout << vector[i] << " ";
break;
}
case 'm':
case 'M':
cout << "test M";
break;
case 's':
case 'S':
cout << "test S";
break;
case 'L':
case 'l':
cout << "test L";
break;
case 'q':
case 'Q':
cout << "Thank you for using the program" << endl;
control_end = true;
break;
default:
cout << "Invalid char. " << endl;
cout << endl;
break;
}
for(auto vec: vector)
cout << vec << endl;
}
while (control_end !=true);
return 0;
}
You created the variable vector inside your loop, so at the end of the loop the variable get destroyed and a new empty one is created on the next iteration. So, if you want your variable to retain values between loop iterations, you should declare it outside of the loop scope, the same way you did with the variable control_end.
So I have a Menu that I used to run my text based game. The problem is that I can't seem to exit my game.Every time I run it, I can do option 1 and go to my game, and options 2 and 3 work just fine. But For option 4, I am unable to exit my game. All it does is print out what I ask it to print out, before giving the menu options again (as if it was just looping).
I have googled a lot, and tried to figure out why but I am not sure.
If someone can advise me what to do or tell me where my mistake is, it would be greatly appreciated. Please let me know if you want to see more code. All I have displayed here is the Menu Function.
void menu() {
char choice = -1;
while(choice != '1')
{
cout << "\n* * * * *" << endl;
cout << " The Dark Maze\n";
cout << "\n* * * * *" << endl;
cout << "\n=====================";
cout << "\n Main Menu |";
cout << "\n=====================";
cout << "\n 1 - Start Game |";
cout << "\n 2 - Instructions |";
cout << "\n 3 - Storyline |";
cout << "\n 4 - Exit |";
cout << "\n=====================";
cout << "\n";
cout << "\n Enter choice: ";
cout << "\n";
cin >> choice;
switch (choice)
{
case '1':
cout << "\n" << endl;
cout << "\n But we can't start the game just yet..." << endl;
break; //heads to game
case '2':
Instructions();
break;
case '3':
Storyline();
break;
case '4':
cout << "\n Well, if you really don't want to play... you don't have to." << endl;
break; //just say exit?? break isnt making it stop
default:
cout << "Invalid Character entered\n";
cout << "\n";
cout << "Press Space to continue\n";
}// end of switches
cin.get();
} // end of while
}// end of menu
You shouldn't be using while loop for this. Try do-while loop for this kind of menus like this:
do
{
// your menu here...
cin >> choice;
switch ( choice )
{
case ...
...
}
// cin.get();
// ^^^^^^^^^^ You don't need this...
} while ( choice != '4' );
Some points to help you:
Use an enum to define your menu choices. (OR an enum class).
You can simply write a printMenu() function to print the menu in the main loop. Another function to process the choice.
For example:
void startGame()
{
char choice = INVALID_OPTION; // INVALID_OPTION => default invalid value
do
{
printMenu();
cin >> choice;
processChoice( choice );
} while ( choice != EXIT ); // EXIT => #define or an enum
}
You can use exit() to terminate your program with a given return value:
case '4':
std::cout << "blahblahblah";
std::exit(0);
break; // No longer necessary
It's prerequisite and prototype is
#include <cstdlib>
namespace std{
void exit(int status);
}
just use return instead break blow case '4' . not perfect but can work.
I have a menu created where the user has to input a number between 1-5, anytime the user inputs a numeric value it works perfect, it will either go to the specified case or in case of an invalid digit, it will go to default and an error message will appear.
Now my problem is when the user inputs an alphabet letter, the program keeps looping and looping, it won't stop, each time going through the default.
I've tried many things! Using an if statement to check whether the number is 1 <= value <= 5, doesn't work. I tried hard-coding in a number if the input is not between those values, it still loops forever. I tried doing cim.good(), not sure if I did it right, but the way I did it doesn't work. I also tried to use the isdigit() function, but same problem, it doesn't work... I really don't know what I gotta do. Here is what I have (simplified).
int menu()
{
int key;
cout << endl << "--------- Main Menu ----------" << endl;
cout << "1: Sort" << endl << "2: Add" << endl;
cout << "3: Search" << endl << "4: History" << endl << "5: Exit" << endl;
cout << "Please pick one: ";
cin >> key;
return(key);
}`
void main()
{
Menu:
key = menu();
switch(key)
{
case 1:
goto Menu;
case 2:
goto Menu;
case 3:
goto Menu;
case 4:
goto Menu;
case 5:
break;
default:
cout << endl << "Invalid entry, please try again" << endl;
goto Menu;
}
}
I deleted what's inside the cases to make it look nicer. When I type in a key, I keep getting the "Invalid entry, please try again" message, so that's where it is going through.
EDIT: Well I apologize for the 'goto', didn't know it was frown upon, still learning! Thank you everyone for all the help though. I will start removing them for sure.
Rather then using goto, I suggest you use a simple do {} while loop like
#include <iostream>
using namespace std;
int menu() {
int key;
cout << endl << "--------- Main Menu ----------" << endl;
cout << "1: Sort" << endl << "2: Add" << endl;
cout << "3: Search" << endl << "4: History" << endl << "5: Exit" << endl;
cout << "Please pick one: ";
cin >> key;
return(key);
}
int main(int argc, char *argv[]) {
int key;
do {
key = menu();
} while (key < 1 || key > 5);
cout << key << endl;
}
Which loops while the key < 1 or the key > 5.
Have a look at this posting from the C++ FAQ lite and this posting.
Checking with cin.good() is the first part of the solution. If a non integer is entered cin.good() will return false. However, the incorrect input will be left in the buffer. So if you encounter the cin >> key again, it will again fail to read anything.
You have to clear the state using cin.clear() and then ignore the rest of the buffer (until end of line) using cin.ignore(INT_MAX, '\n')
So your method would become:
int menu() {
int key;
cout << endl << "--------- Main Menu ----------" << endl;
cout << "1: Sort" << endl << "2: Add" << endl;
cout << "3: Search" << endl << "4: History" << endl << "5: Exit" << endl;
cout << "Please pick one: ";
while(cin >> key) { // same as querying cin.good()
cout << "Not a number" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
return(key);
}
I am coding a banking app for university and i have stumbled upon a problem. Let's take for example a method of my class Customer.
void Customer::create_customer_data() {
cout << "Client' Address: ";
getline(cin, clientAddress);
cin.ignore();
cout << "Client's birth date: ";
getline(cin, clientBirthDate);
cin.ignore();
cout << "Client's telephone number: ";
getline(cin, clientTelephoneNumber);
cin.ignore();
cin.clear(); }
In the main function, i have a switch statement which handles the user choice.
int main() {
int choice, _globalClientNumber = 0;
Customer a(_globalClientNumber);
cout << "Welcome to bank manager 1.0!" << endl;
do {
cout << "Main Menu"<< endl;
cout << "Create a new customer (1)" << endl;
cout << "Create a new account (2)" << endl;
cout << "Cash money into account (3)" << endl;
cout << "Cash money out of account (4)" << endl;
cout << "Transfer money between two accounts (5)" << endl;
cout << "See current status of a customer and its accounts (6)" << endl;
cout << "End Application (0)" << endl;
cout << "Choice: ";
cin >> choice;
switch (choice) {
case 1:
a.create_customer_data();
break;
case 2:
a.create_new_account();
break;
case 3:
a.cash_in();
break;
case 4:
a.cash_out();
break;
case 5:
a.transfer_money();
break;
case 6:
a.print();
break;
default:
break;
}
cout << endl;
}
while (choice != 0);
return 0; }
The problem that i keep having is that the values that are written on the screen by the create_customer_data method are being processed by the do-while loop. So if the clientTelephoneNumber in the create_customer_data does not end in 0, the main menu is shown twice by the do-while loop. I would appreciate it if someone could tell me where my mistake is.
Edit: Shortly said: the choice variable gets overridden and the do-while loop gets executed once more resulting in double printing the menu.
i would say, that your cin needs to be flushed.
the answer can be found here:
How do I flush the cin buffer?
I created a text-based game to help improve my C++ skills since I am very new to it. I'm trying to learn the basics n' all.
Here is the program. In the switch statement, if a person were to select "3" it would broadcast an Error saying you can only select "1" or "2".
** The issue is the program continues and doesn't make the person RECHOOSE the selection. It goes right to Difficulty selecting.
What method do I use to force the program to halt until player chooses valid selection?
Thanks!
#include <iostream>
using namespace std;
int main()
{
cout << "\tWelcome to my text based game!\n";
char userName[100];
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
int pickRace;
cout << "Pick your race: ";
cin >> pickRace;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
}
int difficulty;
cout << "\nPick your level difficulty: \n";
cout << "1 - Easy\n";
cout << "2 - Medium\n";
cout << "3 - Hard\n";
cout << "Pick your level difficulty: ";
cin >> difficulty;
switch (difficulty)
{
case 1:
cout << "You picked Easy" << endl;
break;
case 2:
cout << "You picked Medium" << endl;
break;
case 3:
cout << "You picked Hard" << endl;
break;
default:
cout << "Error - Invalid input, only 1,2 or 3 are allowed" << endl;
}
return 0;
}
You need to use loops. Wrap the input and the switch after it in a loop and break out of it when the input is valid.
Use a do ... while loop, like this
int pickRace;
do
{
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
cout << "Pick your race: ";
cin >> pickRace;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
break;
}
}
while (pickRace != 1 && pickRace !=2);
This will keep on looping while the condition at the bottom is true (i.e. while they haven't picked a valid option).
One other comment. Since you are new you should really get into the habit of using string not char arrays. Char arrays will get you into all sorts of trouble in the future, so start using strings now. There's no point in learning bad habits.
#include <string>
string userName;
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";
You can do - while loop with flags. The flag is by default false therefore allowing only one time input. If there is a need to enter another time, determined and controlled by the default case, then the flag is set to true, which makes the loop iterate once more. At the beginning of each iteration flag is reset to false, so each time it is assumed that this is the last one. Using flag will make the breaking operation much simple, and avoid complex while conditions.
int flag = 0;
do
{
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
cout << "Enter Choice: ";
cin >> pickRace;
flag = 0;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
flag = 1;
}
} while (flag);