开发者

How can I concatenate arguments in to a string in C?

开发者 https://www.devze.com 2023-03-30 02:51 出处:网络
I did something like... str = strcpy(str, arg[1]); str = strcat(str, \" \"); str = strcat(str, arg[2]);开发者_如何学C

I did something like...

str = strcpy(str, arg[1]);
str = strcat(str, " ");
str = strcat(str, arg[2]);开发者_如何学C

what if i have 5 args???

how can i fix it??


Write a loop:

char str[HUGE];
strcpy(str, argv[1]);

for (int i = 2; i < argc; ++i)
{
  strcat(str, " ");
  strcat(str, argv[i]);
}

You should first check that argc is at least 1, and it'd be better to use the lenght-limited functions strncpy and strncat instead, and track the lengths of each argument.


Loops FTW

for(i = 1; i < argc; i++)
{
    str = strcpy(str, arg[i]);
    str = strcat(str, " ");
}

Keep in mind this will add a trailing space at the end. You can remove it by inserting a NUL character at that position. Also do not forget to allocate enough space in str buffer, and to put a terminating NUL character.


You need to firstly check the length of the storage needed. If you have various arguments, the correct answer is using a loop.

int i;
int needed = 1;                        // plus end of string mark

for(i = 1; i < argc; ++i) {
    needed += strlen( argv[ i ] ) + 1; // plus space
}

Then you need to reserve the needed amount of memory, and using another loop, concatenate the strings:

char * storage = (char *) malloc( sizeof( char ) * needed );

strcpy( storage, argv[ 1 ] );

for( i = 2; i < argc; ++i) {
    strcat( storage, " " );
    strcat( storage, argv[ i ] );
}

And finally, use the space and free it.

printf( "%s\n", storage );
free( storage );

Hope this helps.


You can do a loop over arg array. Like

strcpy(str, arg[1]);
strcat(str, " ");

for ( i = 2; i < arg_array_size; i++ )
{
   strcat(str, arg[i]);
   strcat(str, " ");
}


You do not need to assign the returned value to str . Also if your string is stored in a static array then it is not correct.

With the below construct you can concatenate as you want.

char str[MAX];

strcpy (str, "");

for (i=0; i<argc; i++)
{
   strcat (str, argv[i]);
   strcat (str, " ");
}

here argc holds the count of the max elements. Note that the MAX should be large enough to hold all the concatenated strings. You can also do

char *str;
str = malloc (sizeof (char) * MAX);

to allocate memory dynamically. When allocated in this way, please remember to free the allocated memory when you have done working with the string.


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

int main (int argc, char *argv[])
{
  int i;
  int len = 0;
  char *str = "";
  for(i=1; i<argc; i++)
  {
    len += strlen(argv[i]) + 1;
  }
  str = (char *)malloc(sizeof(char) * len);
  for(i=1; i<argc; i++)
  {
    strcat(str, argv[i]);
    strcat(str, " ");
  }
  printf("str = [%s]\n", cmds);
  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号