Copying a char into a char*

I have a class String and one of the constructors to the class is String(char c) where it will copy c into buf which is a char*. I'm having some trouble figuring out how to do this. If anyone could help it would be much appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class String {
protected:
public:
	int length;
	char* buf;
	String();
	String(char*);
	String(char);
	String(const String&);
};

String::String(){
	buf = new char[1];
	strcpy(buf, "");
	length = strlen(buf);
}

String::String(char* a){
        buf = new char[strlen(a) + 1];
	strcpy(buf, a);
	length = strlen(buf);
}

String::String(char c){
   //This is where c would be copied into buf
}
Last edited on
You need to set buf to an array of two chars. Assign c to the first element in the array, and assign 0 (zero) to the second. The zero byte is the null terminator.

Dave
Like dhayden said:

1
2
3
4
buf = new char[2];
buf[0] = c;
buf[1] = 0;
length = strlen(buf);
Topic archived. No new replies allowed.