How to make an exit in switch case implementation with user prompt? - c++

I've a basic computing program, in it I want that when a user wants to just quit the program in his very first input without making any calculation, the program just exits. But rather here if the user enters q for quit/exit in his first input the programs runs into an infinite loop. Is there any way to provide user with some single exit key which when entered anytime(by the user) during runtime just quits the program. The innermost while loop works fine unless the outermost loop stops working.
#include "std_lib_facilities.h"
int main() {
double x = 0, y = 0, result = 0;
string operation = " ";
char op = ' ';
cout << "\nInput (e.g. -> 5*6)\nPress q to quit.\n";
while(1) {
cin >> x >> op >> y;
switch(op) {
case '+':
result = x + y;
operation = "sum";
break;
//Other switch cases
case 'q':
exit(1);
default:
cout << "Invalid input.";
break;
}
cout << "The " << operation << " of " << x << " and " << y << " is "
<< result << ".\n\n"
<< "If you have another input, press any character to continue..\n"
<< "Else press q to quit.\n";
// exit or continue program loop
while(cin >> op) {
if(op=='q' || op=='Q')
exit(1);
else
cout << "Provide next set of inputs.\n";
break;
}
}
}

If the user enter q on the first try then the stream will try to read this value to x which is a double which will fail and the state of the stream will be set to fail, after that no other I/O operation will be successfully performed and the loop will run infinitely.
You could probably check for the state of the stream just before you ask the user to continue or quit and clear the stream state if the previous operation was failed:
if(cin.fail())//check if the previous read operation failed
cin.clear();//clear the stream state,so the next cin will read what is in the buffer
while(cin >> op)
...//your other code

Try this:
boolean quit = FALSE;
while (!quit)
{
...
switch (op)
{
case 'q':
quit = TRUE;
break;
}
}

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char ch;
while(true)
{
cout<<"l.print l "<<endl<<"c.print c "<<endl<<"q. exit"<<endl;
cout<<"enter choice"<<endl;
cin>>ch;
switch(ch)
{
case 'l':
cout<<"You have typed l "<<endl;
break;
case 'c':
cout<<"You have typed c"<<endl;
break;
case 'q':
cout<<"Exit ..." <<endl;
exit(0);
default:
cout<<"Wrong choice "<<endl;
}
}
return 0;
}

Related

How to check if input is valid and keep asking for input if it's not

Can anybody please explain why this while loop is not working properly?
#include <iostream>
using namespace std;
void ask_user(int a, int b){
char choice = ' ';
while(choice != 'q' && choice != 'a' && choice != 's' && choice != 'm'){
cout << "choose operation" << endl;
cout << "a to add, s to subtract, m to multiply and q to quit" << endl;
cout << "----------------------------" << endl;
cin >> choice;
switch(choice){
case 'a' : cout << "a + b = " << a + b;
break;
case 's' : cout << "a - b = " << a + b;
break;
case 'm' : cout << "a * b = " << a + b;
break;
case 'q' : break;
default: cout << "please Enter a valid choice " << endl;
}
}
}
int main(){
ask_user(7, 9);
return 0;
}
If I enter p for exemple which is not valid then it works fine and asks for valid input again,
but if I enter pp that's when it starts bugging and prints the message twice. If I enter ppp it
prints three times etc...
First thing, you have a misunderstanding of how switch works. Each case must end with break statement so that the following one won't get executed.
Which means that a break will break the switch, not the while.
But the main issue is that the logic of your program is wrong.
You should not loop over the validity of the given input, let the switch statement handle that in the default clause.
Instead you should loop over a flag that will be set when the user press the q key.
So considering you have the following functions defined to respectively display the menu and ask for the operands to operate on (defined for code readability):
void display_menu(char & choice)
{
std::cout << "Operation:\na: Addition\nm: Multiplication\ns: Substraction\nq: Quit\n";
std::cin >> choice;
}
void ask_operands(int & a, int & b)
{
std::cout << "\na ?";
std::cin >> a;
std::cout << "\nb ?";
std::cin >> b;
std::cout << '\n';
}
The logic of your code can be then rewritten as:
int main()
{
bool quit = false;
char choice;
int a, b;
ask_operands(a, b); // Ask the user which operands to use
while(!quit) // loop over the flag
{
display_menu(choice);
switch(choice)
{
case 'a': std::cout << (a+b);
break;
case 'm': std::cout << (a*b);
break;
case 's': std::cout << (a-b);
break;
case 'q': std::cout << "Exiting...";
quit = true; // Set the flag to false
break;
default: std::cout << "Invalid choice, try again."; //Here you handle the invalid choices (i.e. let the loop iterate again)
}
std::cout << '\n';
}
return 0;
}
Live example
Note: If you want the user to be able to change the value of the operands at each iteration, just move the ask_operands(a, b); call inside the loop.

Is there a way to input different value for the same data when the same function is called multiple times?

I'm creating a student data management program in C++ and the function to insert examination marks is buggy.
The code given below is enough to recreate the buggy part of the program.
I have tried to increase the size of sub[] to 16
I have tried to insert data one after the other instead of a loop
None of the above seem to solve the problem
Menu function:
char ch;
main_menu:
clrscr();
cout << "Press the key for your choice:\n";
cout << "D -> Edit details\n";
cout << "R -> Get result\n";
cout << "I -> Insert marks\n";
cout << "E -> Exit Program";
choice:
ch = getch();
switch(ch)
{
case 'd':
//edit_nam(); Ignore this one
goto main_menu;
break;
case 'i':
ins_mar();
goto main_menu;
break;
case 'r':
//get_res(); This one is not related to the problem
goto main_menu;
break;
case 'e':
break;
default:
goto choice;
}
Insert marks function:
for(int i = 0; i < 6; i++)
{
clrscr();
cout << "Enter details of subject:" << i + 1;
cout << "\nSubject name:";
cout << "\nMarks:";
gotoxy(14, 1);
cin.getline(student.marks[i].sub, 8);
gotoxy(7,2);
cin >> student.marks[i].mark;
(i != 5) ? cout << "\nPress any key to continue..." : cout << "\nPress any key to return to menu...";
getch();
}
Student structure:
struct stu
{
char name[20];
int ID;
int cls;
mar marks[6];
};
Marks structure:
struct mar
{
char sub[8];
float mark;
}
If the code was working fine, then it would ask the user to enter the marks for all six subjects, every time the function is called in one run.
However, It is not so. In the first time of function call, everything happens in the correct manner, but it does not ask for subject name after first subject in any of the other runs.

How to cause a C++ program to exit

I'm trying to make my C++ program exit.
I know I can pause input with while cin >> s, but I don't know what to do to make the entire program exit.
This is my code:
int main()
{
long int l;
long int i;
char s[100000];
while (cin >> s)
{
l = strlen(s);//strlen Returns the length of the C string str.
for (i = 0; i<l; i++)
{
switch (s[i])
{
case 'W':
cout << "Q"; break;
case 'E':
cout << "W"; break;
case 'R':
cout << "E"; break;
default:
cout << ";"; break;
}
}
cout << (" ");
}
system("pause");
return 0;
}
Your program will terminate when it runs out of input.
The system("pause"); seems to imply that you're using Microsoft Windows. To signal an end-of-file condition for keyboard input on Windows, type Ctrl-Z. (For Linux and other Unix-like systems, use Ctrl-D at the beginning of a line.)
Incidentally, the program you posted is complete and will not compile. That can be corrected by adding the following lines to the top:
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
When posting a question, please include the entire program.
I was able to get the program to exit by using the command exit(0); within the while loop.
Here is my finished program:
include iostream
include string
using namespace std;
int main(){
long int l;
long int i;
char s[100000];
cout << "\n Write your code in UpperCase, "
cout << "to close the program switch to LowerCase \n" << endl;
while (cin >> s)
{
l = strlen(s);//strlen Returns the length of the C string str.
for (i = 0; i<l; i++)
{
switch (s[i])
{
case 'W':
cout << "Q"; break;
case 'E':
cout << "W"; break;
case 'R':
cout << "E"; break;
default:
exit(0); break;
}
}
cout << (" ");
}
system("pause");
return 0;
}
Your loop is waiting until cin >> s returns an "end of file" (EOF). You can accomplish this on Windows by typing Ctrl+Z or on Unix-like systems such as Mac and Linux Ctrl+D.
You could also put a break character in your loop, or change the condition altogether.

C++ How to enter user values without breaking program

I am trying to get an integer from the user but if they type "ckefkfek" it will cause the program to spam and break. I also want them to enter a float but I get the same problem and no clue how to check for this.
int option = 0;
while (option != 3)
{
cout << "Enter 1, 2, or 3: ";
cin >> option;
switch (option)
{
case 1:
cout << "Enter a float: ";
float myfloat;
cin >> myfloat;
myFunc(myfloat); // must be a float for this function to work.
break;
case 2:
// do stuff
break;
case 3:
// do stuff
break;
default:
cout << endl << "Not a valid option." << endl;
break;
}
}
How can I do this without constant errors? Thank you!
bool input_ok = false;
while (!input_ok)
{
cout << "Enter 1, 2, or 3: ";
if (cin >> option)
{
input_ok = true;
...
}
else
{
cout << "Stop being silly\n";
std::string dummy;
if (cin >> dummy)
cin.clear();
else
throw std::runtime_error("OK, I'm not playing any more");
}
}
Basically if the input can fail, you need to test whether it failed. You test that by checking the state of the stream after reading from it, with cin >> option; if (cin) ..., or by combining the read and test like this: if (cin >> option) ...
If input fails, read whatever couldn't be parsed as an integer and discard it, and try again.

Odd looping situation, don't know what's causing it

Having some trouble with some code and I cannot get to the bottom of it. This code:
int main()
{
int choice;
while (choice != -1)
{
system("cls");
std::cout << "Main Menu: " << std::endl
<< " 1. Encode." << std::endl
<< " 2. Decode." << std::endl
<< "-1 to exit." << std::endl;
std::cin >> choice;
switch (choice)
{
case 1:
encode();
break;
case 2:
decode();
break;
case -1:
break;
}
}
getchar();
return 0;
}
void encode()
{
std::string plainText;
std::string encText = "Test";
std::cout << "Enter text to be encrypted.\n";
getline(std::cin, plainText);
for (int x = 0; x < plainText.length(); x++)
{
//encText += plainText.substr(x, x + 1);
}
std::cout << encText;
getchar();
return;
}
If I enter '1' at the first cin >> choice, I go into encode(), once there, entering any text causes the program to go back to the while, perform system("cls"), and then jumps right back to "Enter text to be encrypted." down in encode().
Any help? I'm clueless.
If you'd like to exit your while loop after encode() or decode(), you have to satisty the while's condition. You can do this by simple setting choice to -1 after the function calls:
case 1:
encode();
choice = -1;
break;
case 2:
decode();
choice = -1;
break;
Just so you're aware, the return at the end of encode() causes the encode() function to finish, not main. That line of code actually does nothing; since there's nothing after it, it would happen anyway.