Thread: stdin: Loop taking values - bug with new line character

  1. #1
    Registered User
    Join Date
    Oct 2013

    stdin: Loop taking values - bug with new line character

    I'm trying to take user input, as the user wants.
    - First user enter number, I print it.
    - Second user may enter any thing. I am trying names, or single words. Reading with them fgets, with 100 size.

    Something weird is going on with new line character. I'm simply trying to print input, but this buggy code takes input one less than what I intend to do.

    int main(int argc, char *argv[]){
        char array[100]; //store input.. over write it every time...
        int test=0; //test case .. this decides how many inputs user will give
        printf("%d\n",test); //print your input
            fgets(array,100,stdin); //why it doesn't stop?
            printf("Value is %s\n",array);
        return 0;

    Value is

    Value is jeev

    Value is user

    Value is lol

    There's one new line character with first "value is"

    How do I make fgets stop, to take values that is input? It's printing first time without stopping.

    Should I use fflush or similar things?

    I can set the new line character to '\0', but my concern is, why doesn't stdin stop?

    I can make new line to null character as:
    if(strlen(array) && array[strlen(arrray)-1] == "\n"){
        array[strlen(arrray)-1] == "\0"
    Last edited by deathmetal; 08-13-2015 at 10:47 AM.

  2. #2
    Registered User
    Join Date
    May 2010
    Should I use fflush
    No, fflush() is not defined to be used with an input stream.

    The problem you're having is that scanf() leaves the new line character in the stream which fgets() retrieves as it's only input. So to fix the problem you need to remove the new line character from the stream before your call to fgets(). I believe there is a FAQ entry that tells you how to deal with this problem.


  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Cambridge, UK
    And the FAQ you must be reading.

    You must be looking at the C implementation of my_flush(...) function.

    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 40
    Last Post: 06-28-2012, 12:53 PM
  2. Replies: 1
    Last Post: 11-07-2011, 11:11 PM
  3. Int Array - Stop taking values at [zero]
    By bunko in forum C Programming
    Replies: 3
    Last Post: 12-04-2008, 12:54 AM
  4. Taking inputs at Command Line
    By Stephenf in forum C++ Programming
    Replies: 1
    Last Post: 09-28-2005, 02:33 AM
  5. Moving a character to stdin?
    By DeepBlackMagic in forum C Programming
    Replies: 2
    Last Post: 09-27-2003, 06:37 PM

Tags for this Thread