1

I am trying to create a guessing game where if the player guesses one of many correct strings he will win. Although the switch statement will work with a single letter in the switch parenthesis but it wont work if i put my string in it.

#include "stdafx.h"
#include < iostream>

using namespace std;

class Player
{
public:

    void Guess();
};
void Guess()
{
char guess;
char* word1 = "Dog";
char* word2 = "Cat";


    cout <<"Welcome to guess the word. Get ready..." <<endl;
    cout <<"Guess the word: " <<endl;
    cin >>guess;

    for (int i = 0; i <= 3; i++) //give the player 3 trys at guessing
    {

    switch(guess)
        {
        case 'Dog':
            cout <<"Dog is correct." <<endl;
            i = 3;
            break;

        default:
            cout <<guess <<" is incorrect." <<endl;
            cin >>guess;




        }
    }
}

int main()
{
  Guess();
  char f;
  cin >>f;
  return 0;
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
user3150762
  • 57
  • 1
  • 6

3 Answers3

3

You cannot use switch with strings. This is incorrect:

case 'Dog': ...

Dog is a multibyte character constant, not a string. The compiler should issue a warning about it.

Moreover, guess is a single character. It needs to be a string as well. You should use std::string, like this:

std::string guess;
cout <<"Guess the word: " <<endl;
cin >>guess;
if (guess == "Dog") ...
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

In C++, a switch statement can only compare basic data types, such as int or char. You would need to use a series of if statements to check whole strings, either using the equality operator (==) for std::string objects, or strcmp for C-style strings.

(Be careful not to use the equality operator for C-style strings, as that will only compare the pointer value and not the string content.)

Peter Bloomfield
  • 5,578
  • 26
  • 37
1
  1. Use std::string for the strings to compare.
  2. Replace switch with if(...) { ... } else if(...) {...}

switch-case only works for integral types and 'Dog' is not a single a multi-byte character that could be converted to int but not a string. Note, that strings like "Dog" must be embraced in double-quotes.

Tobias
  • 5,038
  • 1
  • 18
  • 39
  • “`'Dog'` is not a single character that could be converted to `int`.” Actually, it is, though the value is implementation-defined. –  Jan 01 '14 at 16:49