Reputation: 11
#include <iostream>
using namespace std;
int main()
{
enter code here
string grade ='Ahmed';
switch(grade)
{
case 'A' :
cout << "excellent!" <<endl;
break;
case 'B':
cout << "very good!" <<endl;
break;
case 'C':
cout << "well done!" <<endl;
break;
case 'D':
cout << "you passed" <<endl;
break;
case 'F':
cout << "better to try again!" <<endl;
break;
default :
cout <<"invalid grade"<< endl;
}
cout <<"your grade is :"<< grade << endl;
return 0;
}
Upvotes: 0
Views: 83
Reputation: 122133
'Ahmed'
is not a string literal. String literals need "
not single quotes.
How to switch on strings?
You cannot. For switch the condition must be
any expression of integral or enumeration type, or of a class type contextually implicitly convertible to an integral or enumeration type, or a declaration of a single non-array variable of such type with a brace-or-equals initializer.
...and none of this applies for std::string
.
Upvotes: 1
Reputation: 234635
You can't switch on a std::string
in C++: case labels need to be compile time evaluable integral expressions.
'Ahmed'
is actually a multi-character constant (has an int
type but an implementation-defined value): you need to use double quotation characters to declare a suitable type for std::string
construction.
Upvotes: 2