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

}
0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.