Regarding scanf and fgets

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

    Regarding scanf and fgets

    Hi. The following is my code of an example:
    #include <stdio.h> /*line 1*/
    main() /*line 2*/
    {char *command = (char *)calloc(10, sizeof(char)); /*line 3*/
    char *middle = (char *)calloc(10, sizeof(char)); /*line 4*/
    char *name = (char *)calloc(20, sizeof(char)); /*line 5*/
    char *after = (char *)calloc(10, sizeof(char)); /*line 6*/
    /*line 7*/
    scanf("%s", command); /*line 8*/
    scanf("%s\n",mi ddle); /*line 9*/
    fgets(name,20,s tdin); /*line 10*/
    scanf("%s",afte r); /*line 11*/
    /*line 12*/
    printf("Command :%s\n", command); /*line 13*/
    printf("Middle: %s\n", middle); /*line 14*/
    printf("Name:%s ", name); /*line 15*/
    printf("After:% s\n",after); /*line 16*/
    /*line 17*/
    free(command); free(middle); free(name); free(after); } /*line 18*/

    The goal of this example is to take 1 "argument" on each input line (So,this program should take 4 lines in total.), and then print them out.

    My questions are:
    - What are the meaning of \n, [\n], and [^\n] in scanf()?
    - Only using of \n in line 9 will take 1 "argument" on each input line, but not [\n]
    or [^\n] (In the Name field, it seems to be NULL / nothing). Why it happen like
    like this?

    Thanks.
  • nozone
    New Member
    • Oct 2006
    • 4

    #2
    I apologized that I did not show the inputs. The inputs are:

    Add
    the
    Sam
    key

    Thanks

    Comment

    Working...