Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

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

+4 votes
asked Jun 17, 2020 by KingAli2006 (160 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;

}

2 Answers

0 votes
answered Jun 19, 2020 by Peter Minarik (84,720 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;
}
0 votes
answered Jul 6, 2020 by Meet Patel (140 points)
IN string name you do not display hoe many number of string or i would say you do not set any limit to enter your string i thik this could be the problems
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.
...