|
From: <wa...@wa...> - 2004-11-12 23:57:02
|
On 12 Nov 2004 at 18:41, Den...@ao... wrote:
> Please enter the name JACK
> JACK
> Now please enter the name ROBINSON
> ROBINSON
> FirstMix=JAC?-?@
> FirstMix=JAC?-?@ROB
>
> has anybody an idea as to where the extra characters are coming
> from???? thanks in advance.
strncpy does not append a NULL if there isn't a NULL in what it's
copying. So... FirstMix wasn't set to all nulls when it was
initialized and when you copied the first three characters into it,
there was no null to signal the end of the string. You can't assume
that an array of chars will be initialized to null. Sometimes it
will be and sometimes it won't.
You can fix that by either initializing the string to all nulls or by
inserting the null after the strncpy. For example, check out these
modifications to your code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE_OF 15
int main()
{
char FirstName[SIZE_OF], SecondName[SIZE_OF],
FirstMix[SIZE_OF],SecondMix[SIZE_OF];
// used SIZE_OF instead of declaring each array size individualy
strcpy(FirstMix, "123456789");
printf("Please enter the name JACK\n");
scanf("%s", &FirstName);
printf("Now please enter the name ROBINSON\n");
scanf("%s", &SecondName);
strncpy(FirstMix,FirstName,3);
printf("FirstMix=%s\n", FirstMix);
strncat(FirstMix,SecondName,3);
printf("FirstMix=%s\n", FirstMix);
strcpy(FirstMix, "123456789");
strncpy(FirstMix, FirstName, 3);
FirstMix[3] = '\0';
printf("FirstMix=%s\n", FirstMix);
strncat(FirstMix,SecondName,3);
printf("FirstMix=%s\n", FirstMix);
system("pause");
return 0 ;
}
And here's the output:
Please enter the name JACK
JACK
Now please enter the name ROBINSON
ROBINSON
FirstMix=JAC456789
FirstMix=JAC456789ROB
FirstMix=JAC
FirstMix=JACROB
Press any key to continue . . .
HTH.
Watson (the pencil neck) Davis
|