I have to create a program that asks a user to guess a random number 1 to 5, gives a statement for each value, including if they guess the number correct, using a switch statement. I keep getting the same error on just my switch line which says "unqualified id" before switch. Can someone help?
# include <iostream>
using namespace std;
int main()
{
cout << "Enter a digit 1-5";
int number;
cin >> number;
int guess;
cout<<"Enter number to guess";
cin>>guess;}
switch (number)
{
case 1:
{
if (number == guess)
{
cout << "A correct guess!";
}
else
{
cout << "An incorrect guess";
}
break;
}
case 2:
{
if (number == guess)
{
cout << "A correct guess!";
}
else
{
cout << "An incorrect guess";
}
break;
}
case 3:
{
if (number == guess)
{
cout << "A correct guess!";
}
else
{
cout << "An incorrect guess";
}
break;
}
case 4:
{
if (number == guess)
{
cout << "A correct guess!";
}
else
{
cout << "An incorrect guess";
}
break;
}
case 5:
{
if (number == guess)
{
cout << "A correct guess!";
}
else
{
cout << "An incorrect guess";
}
break;
}
}
int main(){
cout << "Enter a digit 1-5";
int number;
cin >> number;
int guess;
cout <<"Enter number to guess";
cin >>guess;
}
switch (number){
case 1:
{
if (number == guess){
cout << "A correct guess!";
}else{
cout << "An incorrect guess";
}
break;
}
case 2:
{
if (number == guess){
cout << "A correct guess!";
}else{
cout << "An incorrect guess";
}
break;
}
case 3:
{
if (number == guess){
cout << "A correct guess!";
}else{
cout << "An incorrect guess";
}
break;
}
case 4:
{
if (number == guess){
cout << "A correct guess!";
}else{
cout << "An incorrect guess";
}
break;
}
case 5:
{
if (number == guess){
cout << "A correct guess!";
}else{
cout << "An incorrect guess";
}
break;
}
}
You left an extraneous closing brace after reading in guess, leaving the switch statement on global scope, outside of any function.
Besides that, the switch doesn't make any sense, since all cases do exactly the same thing. It can be replaced with just
1 2 3 4 5
if (number == guess){
cout << "A correct guess!";
}else{
cout << "An incorrect guess";
}
#include <iostream>
int main()
{
std::cout << "Enter a digit 1-5: ";
int number { };
std::cin >> number;
std::cout << "Enter number to guess: ";
int guess { };
std::cin >> guess;
switch (number)
{
case 1: // let each case switch 'fall through'
case 2:
case 3:
case 4:
case 5:
if (number == guess) { std::cout << "A correct guess!\n"; }
else { std::cout << "An incorrect guess\n"; }
break; // not really needed since there are no other case statements to skip
}
}
Since each case is using the same logic you can remove the switch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
std::cout << "Enter a digit 1-5: ";
int number { };
std::cin >> number;
std::cout << "Enter number to guess: ";
int guess { };
std::cin >> guess;
if (number == guess) { std::cout << "A correct guess!\n"; }
else { std::cout << "An incorrect guess\n"; }
}
Having different output from each case can justify using switch: