Dan Fields
Dan Fields

Reputation: 11

How to work with char* inside a class

I am new to c++ and doing some self training from a text book. I need to create a new class, "String". It must use a constructor to initialize the string to a made up of a repeating character of a sepcified length.

I cannot figure out how to assign anything to a char* variable. Per the assignment I CANNOT use the standard string library to do this. What Do I need to do in my constructor?

#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <string.h>

using namespace std;

class String {
  protected:
    int  _len;

  public:
      char *buff;
    String (int n, char* c);
};

int main()
{
  String myString(10,'Z');
  cout << myString.buff << endl;

  system("PAUSE");
  return 0;
}

String::String(int n, char* c)
{
  buff = new char[n];

}

Upvotes: 1

Views: 351

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You're almost there: since you need repeated character, you shouldn't be passing char*, just a plain char. Also buffers of C strings need to be longer by one character than the string; the last element of the buffer must be the zero character \0.

String::String(int n, char c) {
    buff = new char[n+1];
    for (int i = 0 ; i != n ; buf[i++] = c)
        ;
    buf[n] = '\0';
}

Note that making buf a public member variable is not a good idea: users of String shouldn't be able to reassign a new buffer, so providing an accessor char* c_str() and making buf private is probably a good idea.

Upvotes: 2

Related Questions