Is This Program Correct? If Yes, Then why it is showing error?

0 votes
asked Jun 17 by KingAli2006 (120 points)
#include<iostream>

#include<string>

struct Player

{

 string name;

 int hp;

 Vector position;

 };

 int main()

 {

 Player me;

me.name = "King Ali";

me.hp = 100.0f;

 me.position.x = me.position.y = me.position.z=0;

}

1 Answer

0 votes
answered Jun 19 by Peter Minarik (1,950 points)

What's wrong with the code?

You should include any error you see to help you figure out what's wrong.

First of all, what do you tell the compiler, what language is this?

To kill the suspense, it should not be compiled as a "C" code, but rather as a "C++" code. Or, it can be a "C" code as well, but then you shouldn't include C++ headers, such as iostream. (You can use stdio.h instead to have access to the standard input/output library.) In this case, you cannot use std::string, you have to use char * for strings (or char[] for char arrays).

Also, even though now we've included the right headers, we will need to resolve the namespace. String is within the std namespace. So either you reference it as std::string or you tell the compiler to try to use the std namespace before unknown types: using namespace std.

Also, the type "Vector" is unknown. You have to define it:

struct Vector
{
    float x;
    float y;
    float z;
};

Now your code compiles (but you do not print anything, so not much is visible for the user).

Note: if you want to run this code as a "C" code, instead of "C++", then you have to define the Vector slightly differently. The reason is, that C would require you to reference the type "Vector" as "struct Vector" all the time when you need it. Instead, you can define a type, like this:

typedef struct
{
    float x;
    float y;
    float z;
} Vector;

So, this is how the code should look like in C++:

#include <string>

struct Vector
{
    float x;
    float y;
    float z;
};

struct Player
{
    std::string name;
    int hp;
    Vector position;
};

int main()
{
    Player me;
    me.name = "King Ali";
    me.hp = 100.0f;
    me.position.x = me.position.y = me.position.z = 0.0f;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...