TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: JASON REYNOLDS
from: KURT KUZBA
date: 1997-03-18 02:51:00
subject: Help with Classes

JR>   I would like to know how to store and retrieve char's.
JR>   I've been unable to use chars in a class.
jr>....
   You can use the string handling functions in the string
library. In this case, I would use memmove() to ensure that the
supplied variable does not overrun my allotted char array.
You should also be careful how you use caps, as in Class,
Public, and Private, all of which will produce errors. :)
There is probably a nice iostream method of copying a limited
char array to another char buffer, but I am not that well
versed in the stream classes as of yet. :)
You may also overload the = operator for your assignments in a
class, but the code would remain basically the same and only
the assignment operation calling the code would differ.
//_|_|   CHARS_EX.CPP
//_|_|   Example of using character arrays in classes.
//_|_|   No warrantee or guarantee is given or implied.
//_|_|   Released   PUBLIC DOMAIN   by Kurt Kuzba.  (3/18/97)
#include 
#include 
class PlayerInfo
{
   public:
     int  GetHits() const { return Hits; }
     void SetHits(int h) { Hits = h; }
     const char *GetName() const { return Name; }
     void SetName(const char *N)
     { memmove(Name, N, 32); Name[32] = '\0'; }
   // This ensures that the entire string, up to 32 chars is
   // copied over, and that there is a zero terminator.
   // as an alternative, using sprintf() in stdio.lib
   // void SetName(const char *N) { sprintf(Name, "%.32s", N); }
   // strcpy() may be used, but provides no out of bounds
   // protection for your char array.
   private:
      int Hits;                 // characters Hit Points
      char Name[33];            // characters Name
};
int main(void)
{
   PlayerInfo Player;
   Player.SetHits(40);
   Player.SetName("Player One");
   cout
      << "Player Name: " << Player.GetName() << "\n"
      << "Hit Points : " << Player.GetHits() << endl;
   return 0;
}
> ] Let he among you without sin cast the first... OW! HEY!!....
---
---------------
* Origin: *YOPS ]I[* 3.1 GIG * RA/FD/FE RADist * Milwaukee, WI (1:154/750)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.