char problem in C


Results 1 to 8 of 8

Thread: char problem in C

  1. #1
    Join Date
    Sep 2002
    Posts
    72

    char problem in C

    i have a char array: char x[20];
    i did the following: strcpy(x, argv[2]);

    but i want to add one space in the begining and end of the char array for example say argv[2] is "abc" so i want x to contain " abc " how can i do this?

    thx
    Slackware-current with kernel 2.6.4

  2. #2
    Join Date
    Feb 2000
    Location
    Portland, OR USA
    Posts
    129
    this should pretty much do it
    Code:
    char x[20];
    strcpy(x, " ");
    strcat(x, argv[2]);
    strcat(x, " ");
    ------------------------------------------------------------------
    "Dimensions will always be expressed in the least usable term, convertible only through the use of weird and unnatural conversion factors. Velocity, for example, will be expressed in furlongs per fortnight."

  3. #3
    Join Date
    Sep 2002
    Posts
    72
    Thx very much i could not think of it anyway i am new to C programming....
    Slackware-current with kernel 2.6.4

  4. #4
    Join Date
    Feb 2000
    Location
    Portland, OR USA
    Posts
    129
    Anytime. We're here to help.
    ------------------------------------------------------------------
    "Dimensions will always be expressed in the least usable term, convertible only through the use of weird and unnatural conversion factors. Velocity, for example, will be expressed in furlongs per fortnight."

  5. #5
    Join Date
    Jan 2003
    Location
    Moscow
    Posts
    42
    another way to do that:
    Code:
    int x[20];  
    sprintf(x," %s ",argv[2]);

  6. #6
    Join Date
    Jan 2001
    Location
    Somewhere in middle America
    Posts
    164
    or
    Code:
    char x[20];
    sprintf(x," %.17s ",argv[2]);
    That should ensure the string will actually fit within the allocated space.
    My Machine:
    Maytag SAV5905
    710 rpm Stainless Steel Drum
    Dual boot: Gentoo / Tide

  7. #7
    Join Date
    Sep 2002
    Posts
    72
    Wow prety much C coders here...i want to be a good C coder too thx for different technics..By the way another question i have in the forum about exec()....

    take a look
    Slackware-current with kernel 2.6.4

  8. #8
    Join Date
    Apr 2001
    Location
    SF Bay Area, CA
    Posts
    14,936
    Or

    Code:
    char x[20];
    
    snprintf(x, 20, " %s ", argv[2]);
    (another way to not overflow the buffer).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •