CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: String problem

Threaded View

  1. #1
    Join Date
    Apr 2010
    Posts
    2

    String problem

    I had to program a string class as exercise. I should provide a method concat.

    Whenever I use it the program stops working without showing some error or something else. It just quits and does not process the following lines after I use the concat method.
    I played around and figured out that when I change the signature to
    MyString& concat(MyString& my);

    it works but by copy it does not with the following:
    MyString& concat(MyString my);

    I don't understand that.

    Code:
    My header file:
    #ifndef MYSTRING_H_
    #define MYSTRING_H_
    
    class MyString {
    private:
    	char* characters;
    	int size;
    
    	int length(char* c);
    public:
    	MyString();
    	MyString(char* c);
    	MyString(const MyString& my);
    
    	virtual ~MyString();
    
    	char* toCString();
    
    	MyString& concat(MyString my);
    
    	int getLength();
    };
    
    #endif /* MYSTRING_H_ */
    
    
    MyString class:
    
    #include <iostream>
    #include "MyString.h"
    
    MyString::MyString() {
    	//Init char with size 0
    	characters = new char[1];
    	size = 0;
    	characters[0] = '\0';
    }
    
    MyString::MyString(const MyString& my) {
    	characters = my.characters;
    	size = my.size;
    }
    
    int MyString::getLength() {
    	return size;
    }
    
    MyString::MyString(char* c) {
    	characters = c;
    	size = length(c);
    }
    
    char* MyString::toCString() {
    	return characters;
    }
    
    int MyString::length(char* c) {
    	int i = 0;
    	while(c[i] != '\0') {
    		i++;
    	}
    
    	return i++;
    }
    
    
    MyString& MyString::concat(MyString my) {
    	char* c = my.toCString();
    
    	int l1 = getLength();
    	int l2 = length(c);
    
    	size = l1 + l2;
    
    	char* temp = new char[size+1];	//+1 for \0
    
    
    
    	for(int i = 0; i < l1; i++) {
    		temp[i] = characters[i];
    	}
    	for(int i = 0; i < l2; i++) {
    		temp[l1+i] = c[i];
    	}
    	temp[size] = '\0';	//Termination
    
    
    	//Copy string
    	characters = temp;
    
    
    	return *this;
    }
    
    
    
    MyString::~MyString() {
    	//free memory
    	delete[](characters);
    }
    Last edited by cilu; April 7th, 2010 at 09:32 AM. Reason: code tags

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured