Kamis, 27 Februari 2014

What does %d



up vote-5down votefavorite
1
I'm reading a C program, and I have a question that I think may be related to type casting. Basically, the program will follow. I've commented in a few questions that pasted over from my clipboard. Don't worry about those so much as the question that immediately follows the code block.
/* I only need the out in in/out, right?  Or do I need in and out? */
#include<stdio.h>

/* can someone explain the second argument?  A char is only supposed to be one
character so howcome it has square brackets after it, which indicate an array
to me?  Also, what's with the asterisk? */

int main(int argc,char *argv[])
{
  int i;
/* Here %d is used, which I'm thinking might mean double */
  printf("Amount: %d\n",argc);
  if (argc > 0)
  {
    printf("Parameters:\n");
    for (i = 0;i < argc;i++)
/* Here %s is used, which I'm thinking might mean string */
      printf("%s\n",argv[i]);
  }
  return 0;
}
I'm not sure what the group of %-identified items is called, so I'm not sure where to find a reference of their meanings


down vote
accepted
question 1)
the header file <stdio.h> is included in order to have reference to the input/output function from C library. The <stdio.h> contains only function references and not the definition of the functions. The <stdio.h> contains references to functions like:
·         printf (out) output to stdout (default: screen)
·         scanf (in) reading from stdin (default: keyboard)
question 2)
char *argv[] is an array of pointer. Each pointer element is pointing to a string. Each string is an argument from the command line.
Example: If your program name after compilation is "myprogram" and you calling your program as following:
$myprogram -t test1 test2
So the argv is an array containing 4 pointers to the following string
argv[0] is a pointer to the string "myprogram"
argv[1] is a pointer to the string "-t"
argv[2] is a pointer to the string "test1"
argv[3] is a pointer to the string "test2"
question 3)
%d means integer and not double. For double you can use %lf or %g
question 4)
%s means that you are printing string
example related to argv:
printf("argv[0] = %s\n", argv[0]);
printf("argv[1] = %s\n", argv[1]);
printf("argv[2] = %s\n", argv[2]);
printf("argv[3] = %s\n", argv[3]);
based on question 2 the above prints give the following output:
argv[0] = myprogram
argv[1] = -t
argv[2] = test1
argv[3] = test2

0 komentar:

Posting Komentar