Thread: How to prevent fgets from reading the new line character

  1. #1
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197

    How to prevent fgets from reading the new line character

    Hey guys i am trying to read a string using fgets and storing in an array i want to prevent fgets from storing the new line character on the array using the shortest means possible..

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This is a one version.

    Code:
    int len=strlen(buff); //where buff is your char array fgets is using
    if(buff[len-1]=='\n')
       buff[len-1]='\0';
    You need to include string.h to use strlen().

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    The only way to "prevent" fgets() from storing the newline is to enter exactly as many characters as expected, indicated in the functional call (second argument minus one). This is certainly not an ideal solution.

    Otherwise, you must find and remove the newline yourself. There was quite a discussion on this concept in this thread.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 06-07-2012, 02:50 AM
  2. reading line by from file without fgets
    By gioullis in forum C Programming
    Replies: 1
    Last Post: 12-21-2011, 09:58 AM
  3. Replies: 7
    Last Post: 12-13-2010, 02:13 PM
  4. fgets reading the same line twice
    By lukeaar in forum C Programming
    Replies: 3
    Last Post: 03-25-2010, 06:50 AM
  5. Reading the First Character of the Last Line
    By Ti22 in forum C Programming
    Replies: 1
    Last Post: 04-14-2004, 06:50 AM