#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Scanning a full line and scanning a double/int


    comparing these two programs
    Code:
    #include <stdio.h>
    
    int main()
    {
        char x; // could also be int or double
        scanf("%c", &x);
        getchar();
        printf("x = %c\n", x);
    }
    Code:
    #include <stdio.h>
    
    int main()
    {
        char str[30];
        gets(str);
        printf("[%s]", str);
        getchar();
    }
    the first one doesn't wait for the getchar, but the second one does.
    I know that there's a \n in the buffer after scanning a double, int, char variable, which is why getchar automatically reads it
    but the program does wait for getchar in the second program. on the other hand, when I output the string, the string doesn't have a newline at the end.
    does this mean that gets reads \n, but takes it only as a signal to end the reading, and doesn't store it in the string?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    > does this mean that gets reads \n, but takes it only as a signal to end the reading, and doesn't store it in the string?
    That's exactly what it does, if you had read the manual page to find out.

    Now, having read how it works, you must then erase it from your mind and NEVER use it again.
    http://sourceforge.net/apps/mediawik...php?title=Gets
    Please stick to using fgets() from now on.
    As in say
    fgets(str,sizeof(str),stdin);
    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

IMN logo majestic logo threadwatch logo seochat tools logo