print problem while using fgets()

This is a discussion on print problem while using fgets() within the C Programming forums, part of the General Programming Boards category; Hi all, I'm still new to C and would like to ask the following questions. When I use fgets(), does ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    20

    print problem while using fgets()

    Hi all, I'm still new to C and would like to ask the following questions. When I use fgets(), does it also reads the '\n' character? What should I do if I would like to print in the following manner.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #define MAXSIZE 50
    
    int main(void)
    {
       char *input1, *input2;
       
       input1 = malloc(MAXSIZE);
       input2 = malloc(MAXSIZE);
       
       printf("Input string 1: ");
       fgets(input1, MAXSIZE+1, stdin);
       printf("Input string 2: ");
       fgets(input2, MAXSIZE+1, stdin);
       
       printf("String 1\t\tString 2\n");
       printf("--------------------------------------\n");
       printf("%10s", input1);
       printf("%10s", input2);
       
       return 0;
    }
    Also I would like to ask, is it necessary to do casting when I do malloc, as I sometimes see that being done in C programming books that I read. For example:

    Code:
    char *input1, *input2;
       
    input1 = (char *)malloc(MAXSIZE);
    input2 = (char *)malloc(MAXSIZE);
    Thanks!

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    FAQ > How do I... (Level 1) > Get a line of text from the user/keyboard (C)
    FAQ > Explanations of... > Casting malloc
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Mar 2005
    Posts
    20
    Oh thanks! Sorry for not reading the FAQs. Will keep that in mind in the future.

  4. #4
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    There is no need to have the +1:
    Code:
    fgets(input1, MAXSIZE+1, stdin);
    Change that to this:
    Code:
    fgets(input1, MAXSIZE, stdin);
    And about fgets() sucking in a '\n', fgets() replaces the '\n' with a '\0' (null) character.

  5. #5
    ---
    Join Date
    May 2004
    Posts
    1,379
    >>And about fgets() sucking in a '\n', fgets() replaces the '\n' with a '\0' (null) character.

    It does, does it?

    Code:
    void flush_newline(char *swap){
      /* replaces every '\n' character with a '\0' */
      char ch;
      int i,len;
      len = strlen(swap);
      for(i=0;i<len;i++){
        ch = swap[i];
        if(ch == '\n')
            swap[i] = '\0';
      } 
    }

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by sand_man
    >>And about fgets() sucking in a '\n', fgets() replaces the '\n' with a '\0' (null) character.

    It does, does it?

    Code:
    void flush_newline(char *swap){
      /* replaces every '\n' character with a '\0' */
      char ch;
      int i,len;
      len = strlen(swap);
      for(i=0;i<len;i++){
        ch = swap[ i ];
        if(ch == '\n')
            swap[ i ] = '\0';
      } 
    }
    Which is actually a horrible piece of code because it potentially splits your one string into a bunch of strings. Thus destroying any ability you have to use all of the standard string functions on your one string.

    Also, there is no reason at all for the variable ch.
    Code:
    if( swap[ i ] == '\n' )
        swap[ i ] = '\0';
    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Thanks sand_man, I remember now that it brings a newline with it:

    Code:
    #include <stdio.h>
    #include <al/etl.h>
    #include <sfl.h>
    
    Bool searchNewline( char *userInput )
    {
    	while( *userInput != '\0' )
    		if( *userInput++ == '\n' )
    			return TRUE;
    	return FALSE;
    }
    
    void destroyNewline( char *userInput )
    {
    	while( *userInput != '\0' )
    	{
    		if( *userInput == '\n' )
    		{
    		 	*userInput = '\0';
    			break;
    		}
    		userInput++;
    	}
    	
    }
    
    int main( void )
    {
    	/* VARs */
    	static char userInput[NAME_MAX];
    	
    	
    	/* Get input */
    	fgets( userInput, NAME_MAX, stdin );
    	
    	
    	/* Make sure there are no newlines */
    	while( searchNewline( userInput ) )
    	{
    		puts( "The newline shall vanish" );
    		destroyNewline( userInput );
    	}
    	
    	
    	/* Leave successfully */
    	return EXIT_SUCCESS;
    }
    Output:
    Code:
    hello world!
    The newline shall vanish

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Kleid-0: Why go so far out of your way when the FAQ shows a standard, easier way?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    I just like to practice that's all lol. And I wanted to show myself and others where I messed up in my false remark on my last post. I said that fgets() automatically replaces the '\n' with a '\0' character, but that's wrong, and I wanted to show that here.

    --EDIT--

    omg your right this is a lot easier:
    Code:
    if ((p = strchr(buf, '\n')) != NULL)
          *p = '\0';
    I was trying to remember this when I was doing the function above but I couldn't remember the code. strchr, strchr, strchr.
    Last edited by Kleid-0; 05-14-2005 at 05:57 PM.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Would this work?

    Code:
    if(string[strlen(string)-1] == '\n')
        string[strlen(string)-1] = 0;
    Last edited by dwks; 05-15-2005 at 01:31 PM.

  11. #11
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,451
    string[strlen(string)] is the \0 character
    Use -1 as you did in the assignment.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    If you start out with a string similiar to this:

    "Hello, My name is Joe!\n"

    And you use fgets(); It gives you the string

    "Hello, My name is Joe!\0"

    because it scans to the '\n' then stops and replaces it with '\0'. Then when you use fputs() it prints back out:

    "Hello, My name is Joe!\n"

    because it prints to the '\0' and replaces it with '\n'. When you use strlen(), it scans to the '\0' then stops and does not include the '\0' in the answer. If you have:

    "Hello, My name is Joe!\0"

    It will return a length of 22 instead of 23. I would also like to add that you can just use gets() and puts() if you want to get the string from stdin and put it to stdout.
    Don't quote me on that... ...seriously

  13. #13
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by Brad0407
    If you start out with a string similiar to this:

    "Hello, My name is Joe!\n"

    And you use fgets(); It gives you the string

    "Hello, My name is Joe!\0"

    because it scans to the '\n' then stops and replaces it with '\0'.
    No, it doesn't.
    Quote Originally Posted by Brad0407
    Then when you use fputs() it prints back out:

    "Hello, My name is Joe!\n"

    because it prints to the '\0' and replaces it with '\n'.
    No, it doesn't.
    Quote Originally Posted by Brad0407
    I would also like to add that you can just use gets() and puts() if you want to get the string from stdin and put it to stdout.
    You can use gets if you are a complete idiot, but no one here would recommend it.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. merging linked lists
    By scwizzo in forum C++ Programming
    Replies: 15
    Last Post: 09-14-2008, 05:07 PM
  2. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  3. fgets problem (i think)
    By GanglyLamb in forum C Programming
    Replies: 3
    Last Post: 03-19-2003, 10:19 AM
  4. print output problem
    By chor in forum C Programming
    Replies: 1
    Last Post: 12-29-2002, 08:45 AM
  5. simple shell (c), fgets problem
    By razza in forum Linux Programming
    Replies: 6
    Last Post: 05-26-2002, 10:44 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21