I am not sure if being in linux makes any different, but i have found online that this:
cout << "Press Enter to Continue...";
cin.ignore(numeric_limits<streamsize>::max(),'\n');
Should be sufficient, with #include<limits> in the header of course.
However, it does not seem to work in my program.
It compiles, it runs, but it does not wait.
Basically, i have a menu, which lead to a method call to display a list of people on the screen. I wish to pause that list before the system goes back to the menu.
Here is my code from the menu:
//Manager's Menu
void SelectionPage::showManagerMenu(){
char option;
while(true)
{
system("clear"); //Clears the terminal
cout<<" Flat Manager's Menu"<<endl<<endl; //Display manager's menu
cout << "Select Manager option" << endl;
cout << "a) Add a new Flat Member" << endl;
cout << "b) Delete an existing Flat Member" << endl;
cout << "c) List Flat Members" << endl;
cout << "d) Duties" <<endl;
cout << "e) Resources" <<endl;
cout << "f) Reset System" <<endl;
cout << "q) Exit" << endl;
cout << "make selection: ";
cin >> option;
switch(option) { //Takes the user to the corresponding menu or method
case 'a': system("clear");
memberList.addNewFlatMember(points);
break;
case 'b': system("clear");
memberList.deleteFlatMember();
break;
case 'c': system("clear");
memberList.listFlatMembers();
break;
case 'd': system("clear");
showDutiesMenu();
break;
case 'e': system("clear");
showResourcesMenu();
break;
case 'f': //reset();
break;
case 'q': exit(0);
default: cout << "Option not recognised: " << option << endl;
showManagerMenu();
}
}
}
the option i wish to select is c) which leads to:
//Show the current flat population
void MemberManagement::listFlatMembers(){
cout<<" Member List"<<endl<<endl;
importFlatMembers(); //get flat member info from file
for( int count = 0; count<flatMemberList.size(); count++){
cout << count+1<<". "<<flatMemberList[count].getName() << endl;
}
cout << "Press any key to Continue...";
cin.ignore(numeric_limits<streamsize>::max(),'\n');
return;
}
if you want to see any other bit of my code, feel free to let me know.
Thanks in advance.
Couldn't you just use cin.get() (get one character)?
In *nix, terminals usually wait for a whole line of input before sending anything to the program. Which is why the example code you posted said "Press Enter to Continue...";, and then discarded everything until the next newline.
To avoid that, you should put your terminal in non-canonical mode, which can be done using the POSIX termios(3) functions, as explained in How to check if a key was pressed in Linux?.
Here is a snippet from my code. It works in both windows and linux.
#include <iostream>
using std::cout;
using std::cin;
// Clear and pause methods
#ifdef _WIN32
// For windows
void clearConsole() {
system("cls");
}
void waitForAnyKey() {
system("pause");
}
#elif __linux__
// For linux
void clearConsole() {
system("clear");
}
void waitForAnyKey() {
cout << "Press any key to continue...";
system("read -s -N 1"); // Continues when pressed a key like windows
}
#endif
int main() {
cout << "Hello World!\n";
waitForAnyKey();
clearConsole();
return 0;
}
Related
I'm needing to write a loan program for a course and I have this bit of code thus far:
/*
Project: Course Project - Loan Calculator
Program Description: To calculate customer's loan
information including interest rate, monthly
payment and number of months payments will be
required for.
Developer: ___________
Last Update Date: June 1st, 2020
*/
#include <iostream>
#include <string>
//variables listed here
double loanAmt = 0, intRate = 0, loanLength = 0;
std::string CustName[0];
int choice; //menu choice identifier
using namespace std;
int main()
{
//Welcome User
cout << "Thank you for using our calculator." << endl;
cout << endl;
cout << "Please enter the number of your preferred calculator and press 'Enter': " << endl;
cout << endl;
cin >> choice;
{
while (choice !=4);
switch (choice)
{
case 1:
cout << "Monthly Payment Calculator:";
cout << endl;
break;
case 2:
cout << "Interest Rate Calculator:";
cout << endl;
break;
case 3:
cout << "Payment Term (In Months):";
cout << endl;
case 4:
cout << "Exit Calculator:";
default: //all other choices
cout << "Please Select A Valid Option.";
break;
}
}
}
I've tried moving the cin << choice; to many different spots, including inside of the while loop written for the switch, but I can only seem to get it to show the prompt for the menu, but not the menu options themselves and it isn't taking input. If it makes a difference, I'm using Xcode for the first time and I need it to run there as I can't run C++ on my version of Visual studio (on Mac). Where may I have gone wrong here and any insight into why my version is wrong is appreciated as I'm still very new to coding overall. Thank you.
You had this:
while (choice !=4);
This makes it so that your code never continues further than this while loop. Unless your compiler removes this line during optimization.
This is the correct way:
while (choice !=4) {
switch (choice)
{
case 1:
cout << "Monthly Payment Calculator:";
cout << endl;
break;
case 2:
cout << "Interest Rate Calculator:";
cout << endl;
break;
case 3:
cout << "Payment Term (In Months):";
cout << endl;
case 4:
cout << "Exit Calculator:";
default: //all other choices
cout << "Please Select A Valid Option.";
break;
}
cin >> choice; // have it right after the switch
}
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.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 6 years ago.
I am trying to create a text file that the user inputs the name for. It should just create the text file and then close it, and then give feedback through the terminal if it was created successfully or not. I was able to figure out how to create the file if I hardcoded the file name but now that I am trying it with user input I can't get the file to be created. Right now it doesn't even let me type anything in, it just ends when i call the function. Thank you for your help.
EDIT: I am not sure if it's because my getline call is just getting a blank line then ending or why it won't let me cin anything.
EEDIT: This is my full code,I guess the part I thought wasn't working is, so hopefully somebody can tell me why my code just ends after i select 1 for my switch case. Obviously my code isn't complete, but this is everything I have.
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
void createDB() {
ofstream db;
string filename;
cout << "Enter the name of the database you want to create: \n";
getline (cin, filename);
db.open(filename.c_str());
if(!db) { // checking if the file could be opened
cout << "\nCould not create database\n";
}// add more checks to make sure file doesn't have same name
else {
cout << "\nYour database " << filename << " was created successfully\n";
}
db.close();
}
void openDB() { // just opens hard coded file for now
// need to add check to see if one is already open
cout << "Enter the name of the database you want to open: ";
string line;
//ifstream file (
}
void closeDB() {
}
void display() {
}
void update() {
}
void create() {
}
void add() {
}
void del() {
}
int menu() {
cout << "Enter the number of the operation you wish to perform (1-9)\n"
<< "1. Create new database\n"
<< "2. Open database\n"
<< "3. Close database\n"
<< "4. Display record\n"
<< "5. Update record\n"
<< "6. Create report\n"
<< "7. Add a record\n"
<< "8. Delete a record\n"
<< "9. Quit\n";
int sel = 0;
cin >> sel;
switch (sel) {
case 1: createDB();
//menu(); // after creating file go back to list of options
break;
case 2: openDB();
break;
case 3: closeDB();
break;
case 4: display();
break;
case 5: update();
break;
case 6: create();
break;
case 7: add();
break;
case 8: del();
break;
case 9: return 0;
break;
default: cout << "Please try again and enter a valid number\n\n";
menu();
break;
}
return true; // to avoid error saying control may reach end of non-void function
}
int main() {
menu();
return 0;
}
The piece of code you posted works actually, but it seems getline skips input because of your previous code. So it would be really helpful if you posted the rest of your code.
Therefore because you are using cin before getline you should add std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after cin >> sel;.
So your menu function would be
int menu() {
cout << "Enter the number of the operation you wish to perform (1-9)\n"
<< "1. Create new database\n"
<< "2. Open database\n"
<< "3. Close database\n"
<< "4. Display record\n"
<< "5. Update record\n"
<< "6. Create report\n"
<< "7. Add a record\n"
<< "8. Delete a record\n"
<< "9. Quit\n";
int sel = 0;
cin >> sel;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
switch (sel) {
case 1: createDB();
//menu(); // after creating file go back to list of options
break;
case 2: openDB();
break;
case 3: closeDB();
break;
case 4: display();
break;
case 5: update();
break;
case 6: create();
break;
case 7: add();
break;
case 8: del();
break;
case 9: return 0;
break;
default: cout << "Please try again and enter a valid number\n\n";
menu();
break;
}
return true; // to avoid error saying control may reach end of non-void function
}
I am trying to make my first text-to-play game in C++. The only problem is that the default statement in my code is making the game glitch. I am trying to use another function called exceptionHandler to deal with the default statement, but it doesn't seem to be working. Any suggestions? Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void space(), menu(), exceptionHandler();
int back1, back2;
int main()
{
cout << "Siddiqui Interactive presents..." << endl;
cin.get();
system("CLS");
cout << "Outland" <<endl;
cin.get();
int bob = 0;
//to loop back to main menu
while(bob < 5){
system("CLS");
cout << "Outland" <<endl;
space();
cout << "Press 1 to begin" <<endl;
cout << "Press 2 for credits" <<endl;
cout << "Press 3 to quit" <<endl;
int switch1;
cin >> switch1;
switch(switch1){
case 1:
//nothing here for now
break;
case 2:
system("CLS");
menu();
if(back1 == 1){
system("CLS");
//clears screen to loop back to the menu
}
break;
case 3:
return 0;
break;
default:
system("CLS");
exceptionHandler();
}
}
return 0;
}
void menu(){
//to create a function for the menu, saves time
cout << "This game was coded by: Shahmir Siddiqui and Ibrahim" <<endl;
cout << "Outland was designed by: Azmir Siddiqui" <<endl;
space();
cout << "Press 1 to go back" <<endl;
cin >> back1;
}
void space(){
//just saves time
cout << "" <<endl;
}
void exceptionHandler(){
//to handle exceptions or errors
system("CLS");
cout << "Invalid!" <<endl;
space();
cout << "Press 1 to go back" <<endl;
cin >> back2;
if(back2 == 1){
system("CLS");
//also clears screen to loop back to main menu
}
}
EDIT: Let's say, I typed in d instead of 1, it just keeps on fluctuating rapidly between error screen and main menu.
cin >> switch1 tries to read in an integer. If you type d (which can't be converted to an int, it doesn't "eat" the bad input so you must clear it manually.
Try adding this to your error case:
cin.clear();
cin.ignore(INT_MAX, '\n');
I'm writing a basic program about switch statement. The menu of 5 selections, if the use input invalid number, the user should be prompted again to make a selection (range is from 1-5). Here what I got so far:
#include <iostream>
#include "Menu.h"
using namespace std;
void Menu::inputChoices()
{
int choice;
cout << "IHCC Computer Science Registration Menu" << endl;
cout << "1. Welome to Computer Programming in C++" << endl;
cout << "2. Welcome to Java Programming" << endl;
cout << "3. Welcome to Android Programming" << endl;
cout << "4. Welcome to iOS Programming" << endl;
cout << "5. Exit" << endl;
cout << "\nEnter your selection: " << endl;
while ((choice = cin.get()) != EOF)
{
switch (choice)
{
case '1':
cout << "Welcome to Computer Programming in C++" << endl;
break;
case '2':
cout << "Welcome to Java Programming" << endl;
break;
case '3':
cout << "Welcome to Android Programming" << endl;
break;
case '4':
cout << "Welcome to iOS Programming" << endl;
break;
case '5':
cout << "Exiting program" << endl;
break;
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
}
}
This project has 3 files, this is the source file. My problem is when I input a number is in the range (1-5), the default part of switch still also shows up. I just want show up my selection. Can anyone help me please! Thank you very much
The reason why you are also getting the default value is because cin.get() is reading the newline character (10).
I don't think using cin.get makes sense here since entering something like 23987928 or asdasf will output a ton of lines... You should use cin >> choice and convert your cases into ints. Something like:
cin >> choice;
switch (choice)
{
case 1:
cout << "Welcome to Computer Programming in C++" << endl;
break;
// ...
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
The enter key '\n' should be handled. Try following and see if it works:
while ((choice = cin.get()) != EOF)
{
case 1:
// ...
// Basic idea is read extra `\n` and ignore it. Use below if condition
default:
if(choice != '\n')
cout << "Invalid input. Re-Enter your selection: " << endl;
}