TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: NEIL HELLER
from: ROGER SCUDDER
date: 1998-02-06 00:23:00
subject: C++ SAVEDING STUFF

Hello Neil.
01 Feb 98 10:10, Neil Heller wrote to Anthony Tibbs:
AT>> char s[40];
AT>> fgets (s, 40, stdin);
AT>> printf ("\n\nThis was the string you entered: %s\n", s);
NH> That will STILL give a case of the nasties if the user enters 40
NH> characters.  You must make room for the terminating null.
NH> char s[41];
NH> fgets(s,40,stdin);
 That's a popular myth that is spread around every so often.
 Here's the definition from K&R 2nd edition:
 char *fgets(char *s, int n, FILE *stream)
     fgets reads at most n-1 characters into the array s, stopping
     if a newline is encountered; the newline is included in the
     array which is terminated by '\0'.  fgets returns s or NULL
     if end of file error occurs.
 So, as long as the library writers implemented fgets correctly, it
 is perfectly correct to do it the way Anthony did.
 If you're still not convinced, it's easy to test out...
 
 -------------------------8<--------------------------
 #include 
 #define BUFFER_LENGTH  10
 
 int main()
 {
     char buffer[BUFFER_LENGTH];
     puts( "Enter 1 thru 0 (like this: 1234567890) and press enter." );
     // if fgets works correctly, only 1 thru 9 will be printed.
     //
     fgets( buffer, BUFFER_LENGTH, stdin );
     printf( "%s", buffer );
     return 0;
 }
 --------------------------8<--------------------------
 FYI - It works correctly here.
                                
 -Roger
... 'If it ain't broke, you can probably still fix it.' - Tim Allen
--- Msged 4.20 beta 3
(1:273/404@fidonet)
---------------
* Origin: Hodge-Podge Support BBS, Upper Darby, Pennsylvania, USA

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.