WAAYO ARAG tv
WAAYO ARAG tv

Reputation: 11

how to use string and switch in c++

#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

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

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

Bathsheba
Bathsheba

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

Related Questions