Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in C++ to use string with switch Statement? [duplicate]

Tags:

c++

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;
 }

}
like image 627
Саша Avatar asked Jan 30 '20 15:01

Саша


People also ask

Can you use switch statements with strings in C?

String is the only non-integer type which can be used in switch statement.

Can you use switch statements for strings?

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.

Can you use doubles in switch statements?

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.

Can switch-case have duplicates?

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.


2 Answers

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().

like image 149
JamesS Avatar answered Nov 15 '22 07:11

JamesS


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.

like image 34
anastaciu Avatar answered Nov 15 '22 05:11

anastaciu