So I'm having trouble with classes today, I want to do something like

#include <iostream.h>
using namespace std;
class Dummy{
char Name[256];
void setName(char nam){Name=nam;}
};

int main(){
char[256] temp;
cout << "Name?\n";
cin >>  temp;
setName(temp);
}

I want something like this to store a char array in a class, but it never works, I've googled all this stuff and just cant find it, Help!

Recommended Answers

All 3 Replies

Dummy dum;
dum.setName(temp);

Try this. Comments added explaining the reason for change from your code.

#include <iostream>      // <iostream> is standard, <iostream.h> is not
#include <cstring>        //   need functions to work with C strings

using namespace std;
class Dummy{
char Name[256];

public:    // for main() to use a member function, it must be public
void setName(char *nam)       // arrays are passed to function as pointers
    {strcpy(Name, nam);}   // and char arrays are copied using string functions like strcpy()
};

int main(){
char temp[256];           //   the declaration char [256] temp is invalid
cout << "Name?\n";
cin >>  temp;
Dummy some_object;   //  non-static member functions act on objects
some_object.setName(temp);  // this is how non-static member functions act on objects
}

You also need to put some effort into interpreting and understanding error messages from your compiler. Your compiler would have complained bitterly about your code and, if you'd taken time to understand them, you could worked out the changes I've commented in red.

yeah I actually had it on a seperate pc and didnt ctrl v it onto here, rather quickly interpreted it, my bad, but thx a lot, and one last thing, I tried to add a function called

char getName(){return *Name;}

However it only returns the first letter, god I fail

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.