How to read string from command line argument in C?

How to read string from command line argument in C?

You can print the arguments without transferring them into character arrays. They are null-terminated C strings and printf eats them for breakfast:

for (i=0; i<argc; i++)
  printf(%sn, argv[i]);  

Here is example that converts command line arguments to single string:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    if (argc < 1)
        return 0;

    int i;
    int strsize = 0;
    for (i=1; i<argc; i++) {
        strsize += strlen(argv[i]);
        if (argc > i+1)
            strsize++;
    }

    printf(strsize: %dn, strsize);

    char *cmdstring;
    cmdstring = malloc(strsize);
    cmdstring[0] = ;

    for (i=1; i<argc; i++) {
        strcat(cmdstring, argv[i]);
        if (argc > i+1)
            strcat(cmdstring,  );
    }

    printf(cmdstring: %sn, cmdstring);

    return 0;
}

How to read string from command line argument in C?

argv is a pointer to an array of null-terminated strings. You do not need to know the size of the string; all you need to do is point to the value since the end of the string is indicated with a .

char* init_d = argv[0];
printf(%s, init_d);

If you did want to know the length of the string you could use strlen(argv[0]).

Leave a Reply

Your email address will not be published. Required fields are marked *