I'm doing a assignment for a class at my school and have written this code that follows with little help from DaniWeb users but I have one final touch problem.

The problem is that if I run my strcpy function it always fills out the pzsDestination array to fill out 256 characters so the copy always ends to be 256 char instead of exact copy.

Sample.
If is type in "This is text to copy into another array" then I would get "This is text to copy into another array##################################################################" or until I have 256 char in the array.

Any solutions to that you can see for me, I have tried some ways of doing this and never get the correct answer out of this but my best cuess would not to set the size of the pzsDestination before I use it but then I get error which is (30) : error C2133: 'pszDestination' : unknown size.

Here is the code I have now.

#include <iostream>
using namespace std;

void strcpy( char* pszDestination, char* pszSource, int len = -1);
int strlen(char *pszString);

void strcpy( char* pszDestination, char* pszSource, int len)
{
    if(len == -1) len = strlen(pszSource);
    while(*pszDestination && len)
    {
        *pszDestination = *pszSource;
        pszDestination++;
        pszSource++;
        len--;
    }
}

int strlen( char* pszString )
{
    int i;
	for(i=0; pszString[i]; i++);
    return i;
}


int main()
{
	char pszInput[256]; // Used for storing the input
	char pszDestination[256]; // Used for destination after srtcpy
	int len = -1; // Used for storing the length of the string

	cout << "Enter string (max 255 letters):" << endl;

	cin.getline(pszInput,256);

	cout << endl;

	cout << "The Number of Charaters in.. " <<endl;

	cout << pszInput << endl;

	cout << "is: " << strlen(pszInput) << endl; // Sends the input to strlen to get the size of it.

	cout << endl;

	cout << "Now we copy the text from one string to another... " <<endl;

	cout << "Copying your input to the string called pszDestination" <<endl;

	strcpy(pszDestination,pszInput,len); // Sends the input to strcpy to copy it tp pszDestination

	cout << "pszDestination is now: " << pszDestination << endl;

	cout << endl;

	system("PAUSE");
	return 0;
}

Thanks....
Gvari

Recommended Answers

All 2 Replies

You forget to copy zero char terminated C string.
Can't resist a temptation:

char* StrCpy(char* pd, const char* ps)
{
    char* p = pd;
    while ((*p++=*ps++) != 0);
    return pd;
}

It's a classic self-made strcpy...

Thanks for that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.