hi.i am new to c++.i need to make hangman game for university project.could some on tell me what is the problem with this part of the code?thanks in advance

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <string>
#include <windows.h>
using namespace std;

int main()
    //variable declaration
    string secret_word;

            //randomly print a name of a country from list
            enum Country {PAKISTAN=1,OMAN,IRAN,EGYPT,PHILLIPINES}; //possible names of countries

            int Country=1+rand()%5;
            if (Country==1)
            if (Country==2)
            if (Country==3)
            if (Country==4)
            if (Country==5)
    char data[50];
    int size = 0;       


     size = strlen(data);
    cout << "\nthe number of letters is " <<size;

    return 0;

The problem with this code is firstly that it just doesn't work, but much more problematic it shows some little mis-understandings in the basics of type conversion.

First of consider types: By this I mean the storage for a variable or constant. Examples are int (an integer type), or
double (a floating point number). Those two examples are simple types. C++ allows you to construct your own types and use previously constructed types that you load via libraries. One very common library is the standard template library, which you have loaded part to give you string. It is also why you wrote using namespace std; at the top of your code.

HOWEVER, in the middle of your code you start using char array, (char data[50];) to store 50 char (small unsigned integers really). The try to either compare (because the line data==secret_word; actually evaluates if data is equal to secret_word, BUT you can't do data=secret_word; because data is a pointer to the first memory location in the array of char.

There are ways to convert data, but although all basic types can be converted directly, e.g. (int a; int b(50); a=b;) arrays normally need a more sophisticated copy e.g. you CANNOT do int a[5]; int b[5]={3,4,5,6,7}; a=b; and expect it to work as expected.

To come back to your code, you are using string, and I would have used the string class. e.g.

std::cout<<"Number of letters == "<<secret_word.size()<<std::endl;

Additionally, I would think you should make use of an array to simply you country selections e.g.

const int NWords(5);
std::string CArray[NWords]={"Pakistan","Oman","Iran","Egypt",
int  CNum=rand() % NWords;
std::cout<<"Word choosen == "<<CArray[CNum]<<std::endl;

That way you don't have the long if section and it is easy to add another country when you need to.

This article has been dead for over six months. Start a new discussion instead.