Search code examples
cstring-concatenationargvargc

How to concatenate all of the command line parameters together and print out the resulting value?


I'm having trouble trying to figure out how to concatenate the file path with the strings. The user input the strings in the command prompt like this:

    StringLabMain.exe Mary had a little lamb 1234

It supposed to print out something like this:

    Concatenated arguments: d:\Documents and Settings\labadmin\My Documents\Visual Studio 2012\Projects\test\debug\StringLabMain.exeMaryhadalittlelamb1234

but my code prints out this:

    Concatenated arguments: StringLabMain.exeMaryhadalittlelamb1234

Here is my code (I don't understand how the concatenate works to include the file path with the strings):

    int main(int argc, char *argv[])
    {

      int i;

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

      }
      return 0;
    }

I hope I explained this clearly.


Solution

  • First, if your only purpose is to print the directory and the concatenated args, so you just have to print the current directory before the main loop. This may be done using getcwd().

    #include <stdio.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[])
    {
    
      int i;
      printf("%s", getcwd(0,0));
      for (i = 0; i < argc; i++)
      {
         printf("%s", argv[i]);
      }
      return 0;
    }
    

    But for more general purposes I really recommend you to use stracat() which concatenates string. So you have to declare a "string" (using char *) with the current working directory, and then concatenate the args. This will be done like this way:

    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    
    int main(int argc, char *argv[])
    {
      char* toPrint;
      int i;
      toPrint = getcwd(0,0);
      for (i = 0; i < argc; i++)
        strcat (toPrint, argv[i]);
      printf("%s\n",toPrint);
      return 0;
    } 
    

    I hope that know it's clear.