string class

I am learning how to derive from string class. one of my constructor is as follow:

1
2
3
4
5
6
  String::String(char s){
	char* S = &s;
	buf = new char[1];
	length = 1;
	strcpy(buf,S);
}


but cout<<buf<<endl; gives "Z�p�����*". What am i doing wrong ?
strcpy() expects a null-terminated string for the second parameter.
http://www.cplusplus.com/reference/cstring/strcpy/

As probably does ostream::operator<<, which is printing whatever character the memory contains until it encounters a random 0.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
// C++11:
String::String(char ch) 
    : buf(new char[2]{ch, '\0'}), length(1)
{
}

// or 
String::String(char ch)
    : buf(new char[2]), length(1)
{
    buf[0] = ch;
    buf[1] = '\0';
}


Don't forget your terminating NUL character.
thanks all...
Now I am overloading the operator+. The first call is like this:

String operator+(char *, String&).
I want to combine char* and String& into a char* type, without use strcat().

what is the best approach to this ?

Thanks
closed account (Dy7SLyTq)
strcpy imo
I've tried this

strcpy(buf,char*); // ok this is fine BUT
strcpy(buf,String&); // this will overwrite the first
closed account (Dy7SLyTq)
and why cant you use strcat?
strcat(char*,String&) will modify char*, I don't want that.
Is there a way for strcpy to append instead of overwrite ?
closed account (Dy7SLyTq)
you cant get the string& into the char* without modifying it... and having strcpy append (which it cant do) is exactly what strcat does
You normally want to implement operator+ in terms of operator+=.

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
28
29
30
31
32
33
34
class String
{
    public:
    String(const char* cStr);

    String& operator += (const char*) ;
    String& operator += (const String&) ;
};

String& String::operator+=(const char*cStr)
{
    unsigned cStrLen = std::strlen(cStr) ;
    char* newBuf = new[length + cStrLen + 1] ;

    std::strcpy(newBuf, buf) ;
    std::strcpy(newBuf+length, cStr);

    length += cStrLen ;
    delete [] buf ;
    buf = newBuf ;

    return *this ;
}

inline String operator+(const char* cStr, const String& str)
{
    String result(cStr) ;
    return result += str ;   // C++11:  return std::move(result+=str) ;
}

inline String operator+(String str, const char* cStr)
{
    return str += cStr ;
}

Last edited on
unfortunately it's the other way...char* into string& !
sorry if I sound so 'lost', but i am pretty new to all this.
I already have this

char * buf = new char[strlen(char*) + strlen(string&)];

I am looking for a way to combine char* and string& into newCh* so I can do this.

strcpy(buf, newCh);
thanks cire....this is what I was looking for:

std::strcpy(newBuf+length, cStr);
Topic archived. No new replies allowed.