Thread: fgets

  1. #1
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335

    fgets

    I know basic input about fgets but i'm having trouble on a recursive task i'm trying to do. Basically if <enter> is pressed i want to return; (or just exit out of the program). If something is entered then i want to keep reprompting the user. The problem is since fgets stores the input in an array specified i don't know what to compare to i.e. where exactly do i test if theres a new line? array[0] ?

  2. #2
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    strchr

    Although i don't know what exactly your program is supposed to do - are you
    trying to signal end of input with EOF, and if a newline is pressed instead, quit?
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  3. #3
    Fear the Reaper...
    Join Date
    Aug 2005
    Location
    Toronto, Ontario, Canada
    Posts
    625
    array[0], or maybe all the element in the array to see if any one of them is a newline.
    Teacher: "You connect with Internet Explorer, but what is your browser? You know, Yahoo, Webcrawler...?" It's great to see the educational system moving in the right direction

  4. #4
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    ok i just did:

    Code:
    	if (strcmp(string, "\n") == 0)
    	{
             printf("hello");
    	}
    it might not be elegant enough but it does the job?

  5. #5
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    ugh.. that works but whenever i get rid of the \0 at the end of the string it doesn't work anymore. i.e. after i do:

    Code:
    *p;
    if((p = strchr(string, '\n')))
    	*p = '\0'
    and i can't use strcmp on a specific array if (strcmp(string[0], "\n") == 0))) element because i just get ../test.c:38: warning: passing arg 1 of `strcmp' makes pointer from integer without a cast


    ctrying to signal end of input with EOF, and if a newline is pressed instead, quit?
    yes, basically i just want it to keep running till enter is pressed (it's to exit out of the program)
    Last edited by Axel; 09-15-2006 at 06:25 AM.

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Read one character at a time, or do as suggested, and check your array for \n a character at a time. You know, if you're not going to read what people write, why are you even here?


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    Now i'm confused so I'm gonna try to clear things up:

    You want to read in a string of data from the user - the user will press enter when they have finished, and it will prompt them to enter a string again, unless the string they enter contains only a newline - right?

    In that case, what was wrong with your original solution?

    Now, to explain what you did wrong with your last approaches:

    1. If you read the link on strchr, the whole thing about changing the '\n' to '\0' isn't particularly relevant - what is relevant, is that strchr will return the location in a string of a character, or NULL if the character is not in the string. Now assuming that your quit condition is that the user enters a only a newline, what you want to do is check the address of strchr against the address of the first character in your string - i.e.

    Code:
    if (strchr (string, '\n') == string)
    {
        /*do stuff to quit*/
    }
    2. strcmp(string[0], "\n") - that's wrong because strcmp expects a char * as it's first argument - string[0] is a char.
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  8. #8
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    It's ok i figured it ok. Now what stumples me is that if i feed fgets an array with a size of 16 and 16 as one of its parameters when more than 16 characters is entered it runs it self again with the overflowed characters that were entered (hope that makes sense?)

    i,e:

    Enter something : some character.
    You entered: some character.


    then:

    Enter something : 323222222222222222222222222222
    You entered: 3232222222222222

    Enter something : 22222222222222
    You entered: 22222222222222


    what gives? :|

    Code:
    do {
    			printf("\nEnter something : ");
    			fgets(string, 17, stdin);
    		}
    		while (strcmp(string, "\n") ==1);

  9. #9
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    and for example:

    it prompts the user how many rows over (i.e. if i entered 30 characters and feed fgets 16 it proceeds to prompt me about 4 times)

    Enter something : asdddddddddddddddddddddddddddddddddddddddddddddddd ddddddd

    Enter something :
    Enter something :
    Enter something :
    Enter something :

    full code:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
    	char string[17];
    	do {
    		printf("\nEnter something : ");
    		fgets(string, 17, stdin);
    	}
    		while (strcmp(string, "\n") ==1);
    		return 0;
    	
    }

  10. #10
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    Maybe if you print the string after fgets you'll understand what is going on.

    But to try to explain:
    Code:
    the loop is entered
    "Enter something :" is printed
    You type a string and hit enter
    16 characters of what you typed is consumed by fgets (or less if fewer typed)
    strcmp stanza evaluates to true (by luck)
    the loop is entered
    "Enter something :" is printed
    input is still in the stdin buffer from your previous typing
    16 characters of what you typed is consumed by fgets (or less if fewer left over)
    ....
    Code:
    while (strcmp(string, "\n") ==1);
    This is wrong.
    strcmp may never return 1.
    You probably want != 0, or at least >= 1 which still doesn't make as much sense to me


    BTW you typed more like 57 characters (in the posted example) which is why there were enough characters for 4 fgets calls
    ~/devel/c> bc -l
    57/16
    3.56250000000000000000
    Last edited by spydoor; 09-15-2006 at 09:19 AM.

  11. #11
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    hmm so am i suppose to clear the buffer? tried both !=0 and >0 with the same results :|

  12. #12
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    so just to clarify again:

    i want to keep getting input till i the user hits enter (i.e. a new line).

    hence

    do {
    fgets....... // keep asking for input
    }
    while (strcmp(string,"\n")......... // i.e. while the string has no new lines

    it appears to work however but i want to prevent the buffer overflow problemm and limit it to 16 chars ?

  13. #13
    Learner Axel's Avatar
    Join Date
    Aug 2005
    Posts
    335
    ok fflush worked but is there any other way?

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Like so
    Code:
    #include<stdio.h>
    #include<string.h>
    
    int main ()
    {
        char buff[17];
        while ( fgets( buff, sizeof buff, stdin ) != NULL ) {
            if ( buff[0] == '\n' ) {
                printf( "Blank line entered - bye\n" );
                break;
            } else if ( strchr(buff,'\n') == NULL ) {
                int ch;
                printf( "Scrubbing extra long input\n" );
                while ( (ch=getchar()) != EOF && ch != '\n' );
            } else {
                printf("A good line - %s", buff );
            }
        }
        return 0;
    }
    
    $ ./a.exe
    hello world
    A good line - hello world
    12345678901234567890
    Scrubbing extra long input
    
    Blank line entered - bye
    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.

  15. #15
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >ok fflush worked
    Then you got lucky. fflush is fundamentally not capable of clearing the input buffer. It's designed for flushing an output buffer, which is a completely different task.

    >but is there any other way?
    The best way is to design your code so that you don't need to. Otherwise, you can wimp out and call something like this:
    Code:
    void jsw_flush ( void ) 
    { 
      int ch;
    
      do 
        ch = getchar(); 
      while ( ch != EOF && ch != '\n' ); 
    
      clearerr ( stdin );
    }
    Sadly, we see that kind of code all too often even from Cprog members who should know better.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets not working after fgetc
    By 1978Corvette in forum C Programming
    Replies: 3
    Last Post: 01-22-2006, 06:33 PM
  2. problem with fgets
    By learninC in forum C Programming
    Replies: 3
    Last Post: 05-19-2005, 08:10 AM
  3. problem with fgets
    By Smoot in forum C Programming
    Replies: 4
    Last Post: 12-07-2003, 03:35 AM
  4. fgets crashing my program
    By EvBladeRunnervE in forum C++ Programming
    Replies: 7
    Last Post: 08-11-2003, 12:08 PM
  5. help with fgets
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 10-17-2001, 08:18 PM