c++ default statement will be printed multiple times - c++

void menu() {
char mode = ' ';
cout << "Gebe einen Modus an. 1 Addition, 2 Subtraktion, 3 Multiplikation, 4 Division: ";
cin >> mode;
switch (mode) {
case '1':
addition();
break;
case '2':
subtraktion();
break;
case '3':
multiplikation();
break;
case '4':
division();
break;
default:
cout << "Ungueltige Eingabe, versuch es nochmal\n";
menu();
break;
}
}
Hey! I have the problem, that If I input more than one character, which are not valid, the default statement will be executed just as often as the length of my input. But shouldnt It be like that:
If I input to a char more than one letter, everything after the letter will be cut off, since a char can only save one character. So why does it get executed multiple times? Could anyone explain this, detailed? Thanks in Advance!

Related

Loop control inside void function keeps looping

void getDay() {
bool repeat;
do
{
cout << "Enter the day code (first 2 letters): ";
cin >> weekDay1;
cin >> weekDay2;
weekDay1 = toupper(weekDay1);
weekDay2 = toupper(weekDay2);
switch (weekDay1)
{
case 'M':
break;
case 'T':
break;
case 'W':
break;
case 'F':
break;
case 'S':
break;
default:
cout << "Invalid input. Please try again.\n";
repeat = true;
break;
}
switch (weekDay2)
{
case 'O':
break;
case 'U':
break;
case 'E':
break;
case 'H':
break;
case 'R':
break;
case 'A':
break;
default:
cout << "Invalid input. Please try again.\n";
repeat = true;
break;
}
}while (repeat == true);
return;
}
I need this function to run once, and loop if the input is not one of the accepted characters. I'm trying to prevent any bad input, but it loops infinitely if the input entered on the initial run is not accepted. It works fine if the input is good on the first run, but I keep getting run-time errors for not initializing bools and I need some help adjusting this control.
The condition in the while loop is always true because you never set it to false in its body. You can do something like this:
void getDay() {
// Initializing while declaring is a good practice.
bool repeat = false;
do {
.
.
repeat = false;
.
switch(...) {
...
}
} while (repeat);
}
Now, repeat = true is only called if one of the switch statements invokes default.

(c++)Input needs to be a single character, but it accepts multiple characters and checks the first letter

I'm having a problem with a program I've built.
It should take input from the user and check whether it's 'P' or 'M'.
The problem is that I only want it to work if you enter 'P' or 'M', as it is now it accepts as 'M' anything you type as long as it starts with an 'M' (eg. if you type "morse" it will accept it as 'M').
I'm not a programmer and don't have much knowledge of c++, I just made it for fun. An example of how it is:
int main(){
std::cout << "Enter 'M' or 'P'\n";
char slction;
Inputrror:
std::cin >> slction;
switch (slction) {
case 'M':
goto Morse;
break;
case 'm':
goto Morse;
break;
case 'P':
goto Text;
break;
case 'p':
goto Text;
break;
default:
std::cout << "Please only enter 'M' or 'P'\n;
goto Inputrror;
break;
}
Morse:
std::cout << "Morse\n;"
return 1;
Text:
std::cout << "Text\n;"
return 1;
}
EDIT: I tried to read the input as a string like it was suggested and it now works properly. The correct version:
int main() {
std::cout << "Enter 'M' or 'P'\n";
std::string slction;
Inputrror:
std::cin >> slction;
if (slction == "M" || slction == 'm') {
goto Morse;
}
else if (slction == "P" || slction == 'p') {
goto Text;
}
else {
std::cout << "Please only enter 'P' or 'M'\n";
goto Inputrror;
}
Morse:
std::cout << "Morse\n";
return 1;
Text:
std::cout << "Text\n";
return 1;
}
One comment before I answer:
Instead of
case 'M':
goto Morse;
break;
case 'm':
goto Morse;
break;
you could use
case 'M':
case 'm':
goto Morse;
break;
break stops the block so as long as you don't use it you can nest one after another. You can even do stuff like:
case 'M':
cout << "CAPITALIZED";
case 'm':
goto Morse;
break;
Now, to your question: you are reading a char, meaning it will only take the first letter you input. Use a string instead if you want to be able to read words too:
string slction;
cin >> slction;
PD: remember to change the case 'M' and other options' quotes to double quotes (for strings)
PD2: you can't use switch with strings, so you will have to use if/else blocks
With what was said in the first answer, additionally you could use #include <cctype> toupper() function to remove extra cases. As well as validate your input with if statements.
example validation function:
char isValid(char &selection){
std::cin >> selection;
selection = toupper(selection); // ctype.h for toupper changes all to uppercase characters
//checks to see if more than 1 character is inputed
if (std::cin.get() != '\n'){
std::cin.ignore(256, '\n'); //ignores 256 chars until newline('\n')
std::cin.clear(); // clears the input
selection = '\0'; // sets selection to null
}
return selection;
}
DEMO

what is EOF key in C++

I am using Windows 7 Ultimate. I am new to C++. Following is my exercise for switch statement.
void GradeBook::inputGrades()
{
int grade;
cout << "Enter Grade: " << endl;
while((grade=cin.get()) != EOF)
{
switch(grade)
{
case 'A':
case 'a':
aCount++;
break;
case 'B':
case 'b':
bCount++;
break;
case 'C':
case'c':
cCount++;
break;
case 'd':
case 'D':
dCount++;
break;
case 'F':
case 'f':
fCount++;
break;
case '\n':
case ' ':
case '\t':
break;
default:
cout << "Incorrect data. Re Enter" << endl;
break;
}
}
}
I run this inside netbeans, and I pressed all the combinations ctrl+c , ctrl+z, ctrl+d but it is not ending!! Why is that? Have I done something wrong? Please help!!
An EOF character is Ctrl+Z followed by a newline character on Windows platforms.
Presumably that will be the same for the console within Netbeans.
cin.get() is pretty low level. The code should use a higher-level interface. It's supposed to read a character at a time, so write it that way:
char grade;
while (cin >> grade)
The stream extractor will fail at end of file, and that will make the while loop terminate.

Case command for checking two values

Look at this code please:
char o,t; cin >> o >> t;
switch (o,t)
{
case 's','g': cout << "Finish"; break;
default: cout << "Nothing";
}
as you can see switch is set for two values, but in case command I can not check for both of them at the same time. What should I do? is there any way?
it's not proper syntax use instead
case 's':
case 'g':
cout << "Finish"; break;
You can't switch on multiple values in C++.
switch (o,t)
uses the comma operator (it looks a lot like a pair would in some other languages, but it isn't).
The comma operator evaluates its left operand (o), ignores the value of that, and then returns the value of its right operand (t).
In other words, your switch only looks at t.
There is no way around this.
Your particular case is better written as
if (o == 's' && t == 'g')
{
cout << "Finish";
}
else
{
cout << "Nothing";
}
You cannot do switch for two expressions at the same time. The switch part only compiles because there is a comma operator (which simply evaluates to the second value, in this case t).
Use plain old if statements.
char o,t; cin >> o >> t;
switch (o,t)
{
case 's':
case 'g': cout << "Finish"; break;
default: cout << "Nothing";
}
In switch when matched case is found, all operator after that are executed. That's why you should write break; operator after case-es to exit switch. So if you want to do the same in several cases you should just put them one after another.
You have some syntax error, the correct code is
char o,t; cin >> o >> t;
switch (o)
{
case 's':case 'g': cout << "Finish"; break;
default: cout << "Nothing";
}
switch (t)
{
case 's':case 'g': cout << "Finish"; break;
default: cout << "Nothing";
}

What code should be written to accept Lower and Upper case choices?

I'm beginner to c++ and writing a program that accepts user choices and acts according to it...my only problem is when the user enters Uppercase choice...the program treats it as it's a wrong choice...like if 'e' was a choice for entering a number..if the user entered 'E' the program won't display the "enter the number" message..how can i fix it ? i tried my best but i can't get it working.. Oh , and how can i add the Uppercase in Switch cases ?
This is the part of the code that's responsible of taking user's choice and act according to it.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char choice ;
for(;;){
do{
cout << endl ;
cout << "(e)nter." << endl ;
cout << "(d)isplay." << endl;
cout << "(u)pdate." << endl ;
cout << "(r)eset. " << endl;
cout << "(q)uit." << endl;
cout << endl;
cout << "Choose one : " ;
cin >> choice ;
if( !strchr("edurq",choice) && (choice>=97&&choice<=122) ){
cout << "Enter e,d,u or q " << endl;}
else if( !strchr("EDURQ",choice) && (choice<97&&choice>122) ){
cout << "Enter E,D,U or Q " << endl;}
}while( !strchr("edurqEDURQ",choice) );
switch (choice) {
case 'e' : enter(); break ;
case 'd' : display(); break ;
case 'u': update() ; break ;
case 'r' : reset() ;break;
case 'q' : return 0;
}
}
}
Use the tolower function to convert your input to lowercase and then you will only need to worry about the lowercase options.
If you don't break for a case in a switch statement that matches it will continue on to the next one. If you put the capital cases before each lower case choice it will fall through.
switch (choice) {
case 'E' :
case 'e' : enter(); break ;
case 'D' :
case 'd' : display(); break ;
case 'U' :
case 'u': update() ; break ;
case 'R' :
case 'r' : reset() ;break;
case 'Q' :
case 'q' : return 0;
}
The other option is to apply a string function to the user input to change it to lower case, in which case your existing switch statement would work.
This is a perfect time to use fall through in case statements.
switch (choice)
{
case 'E':
case 'e':
enter();
break;
// etc.
}
Uppercase and lowercase characters use different character codes. So, if you use just lowercase cases in your switch, you will be testing just one type of cases.
You should either improve your switch statement tests, as other exemplified, or convert your choice character to lowercase. This way making sure you are providing the expected case for your switch tests.
Hack it
switch (choice | 0x20) {
...