i had a homework assignment to make a function that does what strncpy does, but my program is supposed to use both my function and the original. well, my function works but the original strncpy won't... any suggestions as to what i might be doing wrong? using dev-cpp 4.9.9.2 windows xp home
Code:
#include <iostream>
#include <cstring>
using namespace std;
void mystrcpy(char dst[], const char src[])
{
int i = 0;
while (src[i] != 0)
{
dst[i] = src[i];
i++;
}
dst[i] = 0;
}
void mystrncpy(char dst[], const char src[], int n)
{
int i = 0;
while (i < n)
{
if (src[i] != 0)
dst[i] = src[i];
i++;
}
dst[i] = 0;
}
int main()
{
char s1[] = "Hello there ";
char result[40];
char s2[] = "Testing my routine";
char result2[40];
char result3[40];
strcpy(result, s1);
cout << "The output string: " << result << endl;
mystrcpy(result2, s2);
cout << "My output string: " << result2 << endl;
strncpy(result,s1, 2);
cout << "The first 2 bytes of the output string: " << result << endl;
mystrncpy(result3,s2, 2);
cout << "The first 2 bytes of My output string: " << result3 << endl;
cin.get();
return 0;
}
so the part where it uses strncpy and specifies that it should only copy the first two characters is where i'm having the problem. in my output it shows that the whole string has been copied.