switch case with string c++
Sure! Here is an example of how to use switch case with string in C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fruit = "apple";
switch (fruit) {
case "apple":
cout << "It's an apple!";
break;
case "banana":
cout << "It's a banana!";
break;
case "orange":
cout << "It's an orange!";
break;
default:
cout << "It's something else";
}
return 0;
}
Explanation: - Include the necessary header files for input/output and string manipulation. - Declare the main function. - Create a string variable "fruit" and assign it a value, e.g., "apple". - Use the switch statement with the string variable "fruit". - Provide cases for different string values, such as "apple", "banana", and "orange". - Include a default case to handle any other string value. - Inside each case, perform the desired operations, such as printing a message. - End the switch statement with a break after each case. - End the main function and return 0.