Re: int array to string?

From: Mike Wahler (mkwahler_at_mkwahler.net)
Date: 04/01/04


Date: Thu, 01 Apr 2004 03:46:28 GMT


"Amittai Aviram" <amittai@amittai.com> wrote in message
news:c4g1pc$2i5f4a$1@ID-124651.news.uni-berlin.de...
> Hi! Is there a convenient way to create a null-terminated string out of
an
> array of type int?

I'm not sure what that means, but I'll take a guess.

> Is there a standard library function I can use? If so,
> how? This seems elementary, but I can't seem to find the right thing --
the
> only thing I can think of is using sprintf repeatedly to push a copy of
the
> next integer from the array onto the growing string, moving the null
> terminator in the process out to the new end,

There's no need to 'move' the terminator, just write over it.
And the terminator indicating the 'new end' will be written
for you by 'sprintf()'.

>until all the integers have
> been converted into characters in the string (provided that I begin with
> adequate memory set aside for this task). But this seems clunky and
> inefficient. Thanks!

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

int main()
{
    int array[] = {1, 2, 3, 4, 5};
    char text[100] = {0};
    char *p = text;
    size_t i = 0;

    for(i = 0; i < sizeof array / sizeof *array; ++i)
        sprintf(p += strlen(p), "%d", array[i]);

    printf("%s\n", text);

    return 0;
}

Output:

12345

You may or may not find my code 'clunky and inefficient',
but that's the way it's done. If it doesn't do what you
want, please clarify.

-Mike



Relevant Pages

  • Off-by-one errors: a brief explanation
    ... the maximum index for the array is N-1. ... that memory location is overwritten ... processes that string will keep accessing memory until it hits a 0 ... terminator value to signify the last element of the array. ...
    (SecProg)
  • Re: problem on method ReadChars
    ... always a terminator at the end of the string, however, the value of the rest ... of array is undetermined (due to the bad coding at linux side). ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Question on networking with custom binary interface.
    ... field after the variable length field is to scan to the null terminator ... classes to parse the former. ... Wrap your own class (even just an array ... key point is that instead of leaving the data as a string and accessing ...
    (comp.lang.ruby)
  • Re: int array to string?
    ... Is there a convenient way to create a null-terminated string ... > out of an array of type int? ... > from the array onto the growing string, ... fixes many of the shortcomings of Windows 98 SE". ...
    (comp.lang.c)
  • Re: problem on method ReadChars
    ... the data in the stream is a 8 bytes char array. ... string with 2 chars to 7 chars. ... As I already have one terminator after the string, ...
    (microsoft.public.dotnet.languages.csharp)

Loading