Question regarding scanf

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nozone
    New Member
    • Oct 2006
    • 4

    Question regarding scanf

    Hi all. I am beginner in C. My question is: What is " \n" inside scanf()?

    Here is part of the implementation of an example:
    ...
    char myChar;
    int myID;
    scanf("%c", &myChar);
    scanf("%d\n"; &myID);
    printf("Option: %c, ID: %d\n", myChar, ID);
    ...
    The reason that I break scanf() into 2 parts is that I need to take either one argument or two arguments from ONE input line depending on what the first argument is. The following is the input line:
    a
    (or)
    b 120

    *a -- I only need one argument.
    *b -- I need two arguments; the second argument is the ID.

    The problem is my program still asking for the next input line before the results are printed. How I can fix it? Thanks.
  • RADAR
    New Member
    • Oct 2006
    • 21

    #2
    Originally posted by nozone
    Hi all. I am beginner in C. My question is: What is " \n" inside scanf()?

    Here is part of the implementation of an example:
    ...
    char myChar;
    int myID;
    scanf("%c", &myChar);
    scanf("%d\n"; &myID);
    printf("Option: %c, ID: %d\n", myChar, ID);
    ...
    The reason that I break scanf() into 2 parts is that I need to take either one argument or two arguments from ONE input line depending on what the first argument is. The following is the input line:
    a
    (or)
    b 120

    *a -- I only need one argument.
    *b -- I need two arguments; the second argument is the ID.

    The problem is my program still asking for the next input line before the results are printed. How I can fix it? Thanks.
    [CODE]
    char myChar;
    int myID;
    scanf("%c", &myChar);
    scanf("%d\n"; &myID);
    printf("Option: %c, ID: %d\n", myChar, ID);
    [\CODE]

    I think you can design and implement your program without using any
    '\n' in scanf because your values can not be executed if you do that.
    [CODE]
    char myChar;
    int myID;
    scanf("%c",&myC har);
    scanf("%d",&myI D);
    printf("Option: %c, \nID:%d\n",mych ar,myID);
    [\CODE]

    the important thing is '\n' in scanf is a logical mistake not a run-time error so your program in hole can work but your values can not be executed.Whenev er you use \n in bracks(" ") compiler will understand there is nothing wrong, the real problem will be seen in executing your values.
    Try to use printf("Option: %c, \nID:%d\n",mych ar,myID); , I mean you wrote ID first so computer will throw away some number into ID.So you must write myID.
    Respects...

    Comment

    Working...