Currently I am trying to get user input by using string with switch, but the compiler is angry and it gives an exception and it closes with an unknown error. This is my code that I am trying.
#include <iostream>
using namespace std;
int main()
{
string day;
cout << "Enter The Number of the Day between 1 to 7 ";
cin >> day;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Attention, you have not chosen the Valid number to Identify weekly days from 1 to 7. Try again!" << endl;
}
}
String is the only non-integer type which can be used in switch statement.
Yes, we can use a switch statement with Strings in Java. While doing so you need to keep the following points in mind. It is recommended to use String values in a switch statement if the data you are dealing with is also Strings.
The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.
If two cases in a 'switch' statement are identical, the second case will never be executed. This most likely indicates a copy-paste error where the first case was copied and then not properly adjusted.
Replace string day
with int day
, or before you go into the switch
, convert day
from a string
to an int
such as with std::stoi()
.
It is not possible to use a string in a switch statement, in this simple example you can replace string day;
with int day;
. If the variable must be a string you can always convert it to an int, there are several tools you can use to do so, strtol
and stoi
to name a couple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With