I'm currently learning about switches in C++, so I created a grading program that will output a specific message based on the grade entered. Below is the code:
#include <iostream>
using namespace std;
int main()
{
char student_grade;
cout << "Enter student's grade:" << "\n";
cin >> student_grade;
// switch statement for a simple grading system
switch(student_grade)
{
case A:
cout << "You have passed with a distinction!";
break;
case B:
cout << "You have a grade B,congrats.";
break;
case C:
cout << "Average grade,you can do better.";
break;
default:
cout<<"NIL grade";
break;
}
return 0;
}
I get this error once I run it, what did I do wrong?
/root/Desktop/practise.cpp: In function ‘int main()’:
/root/Desktop/practise.cpp:14:6: error: ‘A’ was not declared in this scope
14 | case A:
| ^
/root/Desktop/practise.cpp:17:6: error: ‘B’ was not declared in this scope
17 | case B:
| ^
/root/Desktop/practise.cpp:20:6: error: ‘C’ was not declared in this scope
20 | case C:
| ^
In the switch case, the character cases should be written in ' '. E.g. 'A', 'B'. There is a difference between A and 'A', 'A' is a character literal. It's of char type with value 97 on most of the systems.
The corrected code will be:-
#include<iostream>
using namespace std;
int main()
{
char student_grade;
cout<<"Enter student's grade:"<<"\n";
cin>>student_grade;
// switch statement for a simple grading system
switch(student_grade)
{
case 'A':
cout<<"You have passed with a distinction!";
break;
case 'B':
cout<<"You have a grade B,congrats.";
break;
case 'C':
cout<<"Average grade,you can do better.";
break;
default:
cout<<"NIL grade";
break;
}
return 0;
}
Simpe put it in ' ' because thats necessary for chars than it will compile.
Without that its just a variable.
#include<iostream>
using namespace std;
int main()
{
char student_grade;
cout<<"Enter student's grade:"<<"\n";
cin>>student_grade;
// switch statement for a simple grading system
switch(student_grade)
{
case 'A':
cout<<"You have passed with a distinction!";
break;
case 'B':
cout<<"You have a grade B,congrats.";
break;
case 'C':
cout<<"Average grade,you can do better.";
break;
default:
cout<<"NIL grade";
break;
}
return 0;
}
Related
scratching my head on this as it was working just fine earlier but when I went to add some other functions suddenly my program freaked out and I can not get it back to what it was.
class has me writing a rock/paper/scissors program to go up against a computer, any help with why the loop keeps terminating itself would be wonderful
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void RPSout(char);
int RPScomp();
int main() {
char choice;
int endit=0;
while (endit == 0)
{
cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
cin >> choice;
RPSout(choice);
if (choice=='Q'||'q')
{endit=1;}
}
return 0;
}
void RPSout(char choose)
{
int RPS =0;
int comp=0;
switch (choose)
{
case 'R':
case 'r':
{
cout <<"Your choice: Rock";
break;
}
case 'P':
case 'p':
{
cout <<"Your choice: Paper";
break;
}
case 'S':
case 's':
{
cout << "Your choice: Scissors";
break;
}
case 'Q':
case 'q':
{
cout << "Bye Bye Bye";
break;
}
default:
cout<<"You enter nothing!"<<endl;
cout << "The valid choices are R/P/S/Q)";
}
return;
}
int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
unsigned seed = time(0);
srand(seed);
comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
return comp;
}
if (choice=='Q'||'q')
This is equivalent to
if ((choice == 'Q') || 'q')
Which is almost certainly not what you want. 'q' is a non-zero char literal, which is "truthy" and so this expression will never be false. It's akin to writing if (choice == 'Q' || true).
The solution is:
if (choice=='Q' || choice=='q')
The statement
if (choice=='Q'||'q')
always tests true and therefore sets your flag to terminate the loop.
Try:
if (choice=='Q'||choice=='q')
I think your if statement should be if (choice=='Q'|| choice=='q')
Your issue if with the if statement
if (choice=='Q'||'q')
{endit=1;}
the || 'q' part will always be true since 'q' in ASCII is not 0
Change your code to
if (choice=='Q'|| choice=='q')
{endit=1;}
I have a function that declares two object from two different classes :
void car (){
int choice;
cout << " What type of car ? ";
cout <<" 1- Fast . 2- Slow.";
cin >> choice;
switch(choice)
{
case 1:
Fast obj1;
obj1.print();
break;
case 2:
Slow obj2;
obj.print();
break;
default:
cout << "No type";
}
}
The compiler shows error at:
switch(choice)
This is the error
(error: transfer of control bypasses initialization of:
variable "obj1" (declared at line 179)
variable "obj2" (declared at line 181)
Can you please tell me what I am doing wrong
As the error message says, the jump to each switch label passes the initialisation of one or more variables declared inside the switch block, which isn't allowed.
You can fix this by scoping each variable inside a block within the switch block:
switch(choice)
{
case 1:
{
Fast obj;
obj.print();
break;
}
case 2:
{
Slow obj;
obj.print();
break;
}
default: cout << "No type";
}
You have to use blocks in each case Statement if you want to declare variables there:
switch(choice)
{
case 1:
{
Fast obj1;
obj1.print();
}
break;
case 2:
{
Slow obj2;
obj.print();
}
break;
default:
cout << "No type";
}
So I have this assignment for class and I need to use switch statements and the case values must be 2,4,6,8,and 10. The problem is when I use 10 as a case value and then do g++ it says the case label value exceeds the maximum for type. Im not sure what Im doing wrong. Here's my code. It works perfectly if I use any number lower than 10.
#include <iostream>
using namespace std;
int main()
{
char number;
cout << "Enter a number. ";
cin >> number;
switch(number)
{
case '2':
cout << "shoe\n";break;
case '4':
cout <<"door\n";break;
case '6':
cout <<"sticks\n";break;
case '8':
cout <<"straight\n";break;
case '10':
cout <<"big fat hen\n";break;
default:
cout << "Not much into kids' rhymes, ar you?\n" << endl;
}
}
'10' is not a character, it is two characters, which is not allowed. If you want to store numbers, you should not be using the ' characters:
case 8:
cout <<"straight\n";break;
case 10:
...
Instead, you should probably read input as type int.
Don't use the quotes around the numbers.
A char is typically not treated as a number, and certainly not when it comes to reading from a stream. Also, when switching on numbers, don't use character literals:
See commented changes (not tested):
#include <iostream>
using namespace std;
int main()
{
int number; // char isn't a number in this use case, use int
cout << "Enter a number. ";
cin >> number;
switch(number)
{
case 2: // not character literals
cout << "shoe\n";break;
case 4:
cout <<"door\n";break;
case 6:
cout <<"sticks\n";break;
case 8:
cout <<"straight\n";break;
case 10: // '10' is an illegal character literal, as its 2 characters
cout <<"big fat hen\n";break;
default:
cout << "Not much into kids' rhymes, ar you?\n" << endl;
}
}
I'm having trouble with the _getch() function, I want it so that the user does not need to hit ENTER when selecting things from the menu. However, when I try and use it, it either doesn't input the data into a variable, or it skips over the switch I have. I'm using Windows 7, and the CodeBlocks IDE. What am I doing incorrectly? Thanks in advance.
#include <iostream>
#include <sstream>
#include <conio.h>
using namespace std;
stringstream ss;
int a;
void play()
{
cout << "\nYou wake up on the forest floor. You do not remember where you are, who you are, or anything\nthat has happened before you waking up. You seem to be some type of...\n";
cout << "--CHARACTER SELECTION--\n1. Warrior\n2. Mage\n3. Rouge";
cin.get();
};
int main()
{
// CreateDirectory()
cout << "--SELECTION MENU--\n1. Begin\n2. Delete Game\n3. Instructions" << endl;
a=_getch();
switch(a){
case 1:
play();
break;
case 2:
// delete();
break;
case 3:
// help();
break;
return 0;
}
}
Compare your char against the characters '1', '2' and '3' rather than the integers 1, 2 and 3.
switch(a){
case '1':
play();
break;
case '2':
// delete();
break;
case '3':
// help();
break;
return 0;
}
I would like to use an enum value for a switch statement. Is it possible to use the enum values enclosed in "{}" as choices for the switch()"?
I know that switch() needs an integer value in order to direct the flow of programming to the appropriate case number. If this is the case, do I just make a variable for each constant in the enum statement?
I also want the user to be able to pick the choice and pass that choice to the switch() statement.
For example:
cout << "1 - Easy, ";
cout << "2 - Medium, ";
cout << "3 - Hard: ";
enum myChoice { EASY = 1, MEDIUM = 2, HARD = 3 };
cin >> ????
switch(????)
{
case 1/EASY: // (can I just type case EASY?)
cout << "You picked easy!";
break;
case 2/MEDIUM:
cout << "You picked medium!";
break;
case 3/HARD: // ..... (the same thing as case 2 except on hard.)
default:
return 0;
}
You can use an enumerated value just like an integer:
myChoice c;
...
switch( c ) {
case EASY:
DoStuff();
break;
case MEDIUM:
...
}
You're on the right track. You may read the user input into an integer and switch on that:
enum Choice
{
EASY = 1,
MEDIUM = 2,
HARD = 3
};
int i = -1;
// ...<present the user with a menu>...
cin >> i;
switch(i)
{
case EASY:
cout << "Easy\n";
break;
case MEDIUM:
cout << "Medium\n";
break;
case HARD:
cout << "Hard\n";
break;
default:
cout << "Invalid Selection\n";
break;
}
Some things to note:
You should always declare your enum inside a namespace as enums are not proper namespaces and you will be tempted to use them like one.
Always have a break at the end of each switch clause execution will continue downwards to the end otherwise.
Always include the default: case in your switch.
Use variables of enum type to hold enum values for clarity.
see here for a discussion of the correct use of enums in C++.
This is what you want to do.
namespace choices
{
enum myChoice
{
EASY = 1 ,
MEDIUM = 2,
HARD = 3
};
}
int main(int c, char** argv)
{
choices::myChoice enumVar;
cin >> enumVar;
switch (enumVar)
{
case choices::EASY:
{
// do stuff
break;
}
case choices::MEDIUM:
{
// do stuff
break;
}
default:
{
// is likely to be an error
}
};
}
You can use a std::map to map the input to your enum:
#include <iostream>
#include <string>
#include <map>
using namespace std;
enum level {easy, medium, hard};
map<string, level> levels;
void register_levels()
{
levels["easy"] = easy;
levels["medium"] = medium;
levels["hard"] = hard;
}
int main()
{
register_levels();
string input;
cin >> input;
switch( levels[input] )
{
case easy:
cout << "easy!"; break;
case medium:
cout << "medium!"; break;
case hard:
cout << "hard!"; break;
}
}
I had a similar issue using enum with switch cases.
Later, I resolved it on my own....below is the corrected code, and perhaps this might help.
//Menu Chooser Programme using enum
#include <iostream>
using namespace std;
int main()
{
enum level{Novice=1, Easy, Medium, Hard};
level diffLevel = Novice;
int i;
cout << "\nEnter a level: ";
cin >> i;
switch(i)
{
case Novice:
cout << "\nyou picked Novice\n"; break;
case Easy:
cout << "\nyou picked Easy\n"; break;
case Medium:
cout << "\nyou picked Medium\n"; break;
case Hard:
cout << "\nyou picked Hard\n"; break;
default:
cout << "\nwrong input!!!\n"; break;
}
return 0;
}
You should keep in mind that if you are accessing a class-wide enum from another function, even if it is a friend, you need to provide values with a class name:
class PlayingCard
{
private:
enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };
int rank;
Suit suit;
friend std::ostream& operator<< (std::ostream& os, const PlayingCard &pc);
};
std::ostream& operator<< (std::ostream& os, const PlayingCard &pc)
{
// Output the rank ...
switch(pc.suit)
{
case PlayingCard::HEARTS:
os << 'h';
break;
case PlayingCard::DIAMONDS:
os << 'd';
break;
case PlayingCard::CLUBS:
os << 'c';
break;
case PlayingCard::SPADES:
os << 's';
break;
}
return os;
}
Note how it is PlayingCard::HEARTS and not just HEARTS.
The user's input will always be given to you in the form of a string of characters... if you want to convert the user's input from a string to an integer, you'll need to supply the code to do that. If the user types in a number (e.g. "1"), you can pass the string to atoi() to get the integer corresponding to the string. If the user types in an english string (e.g. "EASY") then you'll need to check for that string (e.g. with strcmp()) and assign the appropriate integer value to your variable based on which check matches. Once you have an integer value that was derived from the user's input string, you can pass it into the switch() statement as usual.
#include <iostream>
using namespace std;
int main() {
enum level {EASY = 1, NORMAL, HARD};
// Present menu
int choice;
cout << "Choose your level:\n\n";
cout << "1 - Easy.\n";
cout << "2 - Normal.\n";
cout << "3 - Hard.\n\n";
cout << "Choice --> ";
cin >> choice;
cout << endl;
switch (choice) {
case EASY:
cout << "You chose Easy.\n";
break;
case NORMAL:
cout << "You chose Normal.\n";
break;
case HARD:
cout << "You chose Hard.\n";
break;
default:
cout << "Invalid choice.\n";
}
return 0;
}
You can cast enum with int.
enum TYPE { one, two, tree };
TYPE u;
u = two;
switch( int( u ) ){
case one :
action = do_something ;
break;
case two:
action = do_something_else;
break;
}