how to use string variable in switch case in c++
Sure! Here is an example of how to use a string variable in a switch case in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fruit;
cout << "Enter a fruit: ";
cin >> fruit;
switch (fruit[0]) {
case 'a':
cout << "You entered an apple." << endl;
break;
case 'b':
cout << "You entered a banana." << endl;
break;
case 'c':
cout << "You entered a cherry." << endl;
break;
default:
cout << "You entered an unknown fruit." << endl;
break;
}
return 0;
}
Explanation:
First, include the necessary header files:
iostream
for input/output operations andstring
for handling string variables.Declare a string variable
fruit
to store the input.Prompt the user to enter a fruit using
cout
.Read the input from the user and store it in the
fruit
variable usingcin
.Use the switch statement to check the first character of the
fruit
string by accessing it withfruit[0]
.Inside the switch statement, define cases for each possible value of the first character.
In each case, provide the desired output. For example, if the first character is 'a', output "You entered an apple." using
cout
.Use the
break
statement after each case to exit the switch statement.Add a
default
case to handle any unknown fruits that were entered. In this case, output "You entered an unknown fruit."Finally, return 0 to indicate successful program execution.
This code snippet demonstrates how to use a string variable in a switch case statement in C++. The program prompts the user to enter a fruit and then checks the first character of the inputted string to determine the corresponding case in the switch statement. The program outputs a message depending on the entered fruit or if it is unknown.