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

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Scanf with strings


    Is %s capable of ignoring newlines?

    I know that for the code
    Code:
    #include <stdio.h>
    
    int main()
    {
        char c1, c2;
        scanf("%c", &c1);
        scanf("%c", &c2);
        printf("|%c||%c|", c1, c2);
    }
    if I enter
    Code:
    a[enter key]b
    the output will be
    Code:
    |a||
    |
    I wondered if I the same problem would happen with %s.
    Here's the code for this experiment:
    Code:
    #include <stdio.h>
    
    int main()
    {
        char names[4][10];
        int i;
        scanf("%s", names[0]);
        scanf("%s", names[1]);
        printf("%s\n%s", names[0], names[1]);
    
    }
    I entered
    Code:
    John[enter key]Michael
    and got the output
    Code:
    John
    Michael
    It seems that %s is capable of ignoring newlines from the experiment.
    Is this really the case?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,381
    Rep Power
    1871
    %s ignores all white-space to begin with (and that includes newlines).
    %c doesn't ignore anything at all, it always takes the next character from the input stream.

    If you want the next non-space character when using %c, then do this.
    Code:
    #include <stdio.h>
    
    int main()
    {
        char c1, c2;
        scanf(" %c", &c1);  // note the initial space in the format.
        scanf(" %c", &c2);
        printf("|%c||%c|", c1, c2);
    }
    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
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2
    I see, thank you.

IMN logo majestic logo threadwatch logo seochat tools logo