Thread: fgets in a function subroutine

  1. #1
    Polar Fuzz
    Join Date
    Oct 2003
    Posts
    36

    fgets in a function subroutine

    The following code works fine if run from the main but the SAME code will not function at all from a subroutine. It is designed to read input from the keyboard and assign it to a char string. If I run it from the subroutine (insertString listed below), it does not pause to ask for input, but just keeps going to the next line of code. This does not happen if run from main. Do you know why it only works in the main, and is this just a restriction of C?

    [code]
    void insertString (void);

    /*WORKS FINE FROM MAIN*/
    int main (void) {
    char sourceString[100];
    printf ("\n\tEnter a Source String: ");
    fgets (sourceString, sizeof (sourceString), stdin);
    printf ("\nSource String is %s", sourceString);
    system("pause");
    return 0;
    }

    /* NOT WORK FOR SUBROUTINE*/
    void insertString (void) {
    char sourceString[100];

    printf ("\n\tEnter a Source String: ");

    fgets (sourceString, sizeof (sourceString), stdin);

    printf ("\nSource String is %s", sourceString);

    } /* end function insertString */
    [code]

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    1. Learn how to use code tags properly, or at least how to press "preview" before submit.

    2. You don't show how you call your subroutine

    3. More likely, you're calling scanf() before calling your subroutine, which as everyone knows is a real killer for following fgets() calls.
    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

Similar Threads

  1. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 07:05 PM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM