In a c++ tutorial this was one way to define a string

#include <string>
using namespace std;

string name;
name="mark";

But it dosent work i get errors.Why is this?

Recommended Answers

All 7 Replies

Don't you think you need a Main() function?

Don't you think you need a Main() function?

yes a got a main function

#include <iostream>
#include <string>
string name;
name="mark";

int main()
{
     cout<<name;
     return 0;
}
#include <iostream>
#include <string>


int main()
{
string name;
name="mark";
     cout<<name;
     return 0;
}

or maybe:

#include <iostream>
#include <string>
string name("mark");  //this is initialization, not assignment


int main()
{
     cout<<name;
     return 0;
}

However, I don't think you can assign values to global variables outside of a function.

Thx that worked but now i want to put a string in a class i tryed this

#include <iostream>
#include <string>

class Name
{
     string myname;
public:
     Name();
     ~Name();
     void print();
};
Name::Name()
{
     myname="mark";
}
Name::~Name
{
}
void Name::print()
{
     cout<<myname;
     
}
int main();
{
     Name firstname;
     firstname.print();
     return 0;
}

Didnt work

never mind got it working:)

Thx that worked but now i want to put a string in a class i tryed this Didnt work

I have highlighted the section which you forgot towrite or had wrongly written.

Try this

#include <iostream>
#include <string>

class Name
{
     string myname;
public:
     Name();
     ~Name();
     void print();
};

Name::Name()
{
     myname="mark";
}
Name::~Name ()
{
}
void Name::print()
{
     cout<<myname;
     
}
int main();
{
     Name firstname;
     firstname.print();
     return 0;
}

It would be really better if you started C++ using some basic c++ tutorials, get the basics straight, read some theory and then start programming.

Hope it helped,
bye.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.