Mail Archives: djgpp/1997/09/27/18:15:35
Paul Fitzgibbons wrote:
>
> Hi there
>
> just like to say that I am enjoying learning with DJGPP and have also got
> the Allegro Library from Shawn Hargreaves.
>
> I have a problem with the following code. When inputting strings of up to 20
> chars there doesnt appear to be a problem but if i input a string of length
> 21 or greater the string then ends in funny characters. I thought strncpy
> would have avoided this? I am able to write a function to check if the
> length is greater and to loop if it is, but i would rather do it by
> shortening the string.
>
> Any help will be much appreciated.
>
> Many thanks Paul Fitz
>
> [code follows]
>
> #include <stdio.h>
> #include <string.h>
> #include <stdlib.h>
>
> struct DETAIL
> {
> char name[21]; //max length +1 for NULL
> };
>
> void dispstru(struct DETAIL *ptr);
>
> main()
> {
> struct DETAIL Personal_info;
> struct DETAIL *Personal_info_ptr;
> char buff[1024]; //nice and long to avoid errors
>
> printf("What is the name? : ");
> gets(buff);
>
> strncpy(Personal_info.name,buff,20); //copy 20 chars
>
> printf("name is : %s",Personal_info.name);
>
> Personal_info_ptr=&Personal_info;
> dispstru(Personal_info_ptr);
> }
>
> void dispstru(struct DETAIL *ptr)
> {
> printf("Pointer to name = : %s ",ptr->name);
> }
Your problem is when the length of the string to be copied is longer
than 20 characters strncpy() does NOT place a terminator on the
resulting string. You will have to do that yourself. This behavior is
in accord with the ANSI/ISO Standard.
BTW, If you use fgets() instead of gets() you can specify the length of
the input.
fgets(buffer, 21, stdin );
gets() is a really horrible function an should probably never be used.
--
************************************************
* Alicia Carla Longstreet carla AT ici DOT net *
* Remove the _JUNK_ when replying to me. *
************************************************
My programming is Wobbly. It's good programming but it Wobbles,
and the statements sometimes get in the wrong places.
************************************************
C appeals due to is simplicity and elegance.
- Raw text -