FidoNet Echomail Archive
aust_c_here

<<< Previous Index Next >>>

From: andrew clarke
To: Joshua Marshall
Date: 1996-12-17 11:58:08
Subject: sprintf function

09 Dec 96 11:29, Joshua Marshall wrote to All:

 > Can somebody tell me the easiest way to do this:

 > I want to insert a character into a string.  I have tried:

 >   sprintf(string, "%c%c%s", string[0], '0', string+1);

 > however if string is "TEST" instead of "T0EST" I
am getting "T0000"

 > This is using SAS/C v 6.57 for the Amiga.  Can somebody tell me if it's 
 > just the compiler?

Watcom C/C++ 10.0 and EMX 0.9c exhibit the same behaviour.  Borland C++ for
OS/2 1.0 does not.  I get "T00" with MetaWare High C/C++ 3.2.

I suggest you use a temporary variable to store "TEST", eg.

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

#ifdef NEED_STRDUP

char *strdup(const char *str)
{
    char *ptr;

    if (str != NULL)
    {
        ptr = malloc(strlen(str) + 1);
        if (ptr != NULL)
        {
            strcpy(ptr, str);
        }
        return ptr;
    }

    return NULL;
}

#endif

int main(void)
{
    char string[80], *temp;
    temp = strdup("TEST");
    if (temp != NULL)
    {
        sprintf(string, "%c%c%s", temp[0], '0', temp + 1);
        printf("`%s'\n", string);
        free(temp);
    }
    return 0;
}

Regards
Andrew

-- randy{at}zws.com

--- Msged/2 4.10 beta 1
 * Origin: Blizzard of Ozz, Melbourne, Australia (3:635/728.4{at}fidonet)
SEEN-BY: 633/267 270

@PATH: 633/267


<<< Previous Index Next >>>