Thread: newline and null terminator

  1. #1
    Registered User
    Join Date
    Apr 2010

    newline and null terminator

    I would like some help to check if I am understanding this properly.

    Lesson 9 - Cstrings ( states

    "fgets will read input until it either has no more room to store the data or until the user hits enter." (the user can only hit enter once for this type of input? we can not use "paragraphs" if you know what I mean?)

    "The one thing to watch out for when using fgets is that it will include the newline character ('\n') when it reads input unless there isn't room in the string to store it. This means that you may need to manually remove the input. One way to do this would be to search the string for a newline and then replace it with the null terminator."

    Why do we need to remove the newline character?
    a. because when we call the string to printf it will print the text and the actual backslash n ('/n')
    b. if our array is 256 in size and the newline character is stored in the last element array[255] we need to remove it to fit the null character '\0', otherwise we cant call the string

    or is there another reason we need to get rid of the newline character?


  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    1. That is correct -- once you hit enter, you're done.
    2. Because in >95% of situations it is incorrect to store the \n with the data, as it is not part of the data. Your name doesn't have a new-line in it. Neither does your telephone number, or a book title, or ....

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Quote Originally Posted by dunsta
    Why do we need to remove the newline character?
    (a) would be a correct reason (but then you don't necessarily need to remove it). (b) is incorrect, since there must be space for the null terminator to begin with.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-16-2009, 06:00 AM
  2. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  3. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  4. A bullet-proof fgets wrapper?
    By n7yap in forum C Programming
    Replies: 15
    Last Post: 12-16-2004, 05:19 PM
  5. mygets
    By Dave_Sinkula in forum C Programming
    Replies: 6
    Last Post: 03-23-2003, 07:23 PM