Home>

I'm a C beginner who has recently started studying and studying C.
I am currently creating a program that uses command line arguments (argc, argv []) to concatenate and display strings.

* If the command line argument is "abc_123_def", I want to output "abc123def".

Please tell us if you have any suggestions or hints.

Source code
/* ---------- Return the length of the string ---------- * /
int str_length (char s []) {
    int len ​​= 0;
    while (s [len])
        len ++;
    return len;
}

int main (int argc, char * argv [])
{
    / *
    * When the command line argument is "abc 123 def"
            [0] [1] [2] [3] [4] ...
    argv [1] a b c \ 0
    argv [2] 1 2 3 \ 0
    argv [3] d e f \ 0
    .
    .
    .
    * /
    int i;
    int j = 0;
    int wlen;
    printf ("For confirmation: Total number of arguments =% d \ n", argc);
    for (i = 1;i<argc;i ++)
    {
        wlen = str_length (argv [j]);
        for (j = 0;j<wlen;j ++)
        {
            printf ("% s",&argv [i] [j]);
            j ++;
            return j;
        }
    }

    getchar ();
    return 0;
}
Supplemental information

It seems that you can use the standard function "strcat", but if you have any hints about it, please tell us.

  • Answer # 1

    There is no need to think so hard because it simply outputs the elements in order.

    for (int i = 1;i<argc;++ i) {
        printf ("% s", argv [i]);
    }
    printf ("\ n");

    In addition to what otn pointed out, one more thing.

    wlen = str_length (argv [j]);

    Isn't argv [j] not argv [j] to pass here?

  • Answer # 2

    for (j = 0;j<wlen;j ++)
            {
                printf ("% c", argv [i] [j]);
            }


    is not it. In addition to how to useprintf, there is a problem ofreturnthat incrementsjtwice.

  • Answer # 3

    # include<stdio.h>
    #include<string.h>
    int main (int argc, char * argv []) {
      char str [BUFSIZ] = "";
      for (int i = 1;i<argc;i ++) {
        strncat (str, argv [i], BUFSIZ-1);
      }
      printf ("% s \ n", str);
    }

    Reference information

    [C language] Concatenating strings [Dangerous strcat and string concatenation with safe snprintf function]