Thread: fgets and a bothersome newline char

  1. #1
    Registered User ivandn's Avatar
    Join Date
    Oct 2001
    Posts
    49

    fgets and a bothersome newline char

    Hi!

    I am using fgets instead of gets for input to prevent possible buffer overrun.

    When a string is read, a newline character is included at the end of the string. Do you have to manually remove this newline char after every read, or write your ownn function to do this everytime or ..... is there a better way to deal with this extra newline that anyone has used before?

    Thanks
    Ivan

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    use strchr, as shown here
    http://www.eskimo.com/~scs/C-faq/q7.1.html

    You can always write a 'my_gets()' which has all the safety of fgets, and deletes the newline if it's present.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed