6

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

}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Саша
  • 837
  • 4
  • 12

2 Answers2

8

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
8

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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JamesS
  • 2,167
  • 1
  • 11
  • 29