473,385 Members | 1,344 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

int array to string?

Hi! Is there a convenient way to create a null-terminated string out of an
array of type int? 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, 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!

Amittai Aviram

Nov 14 '05 #1
7 9908
On Wed, 31 Mar 2004 22:20:10 -0500, "Amittai Aviram" <am*****@amittai.com>
wrote:
Hi! Is there a convenient way to create a null-terminated string out of an
array of type int? 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, 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!
There's nothing standard for converting an unbounded quantity of binary
data into text; to me, it doesn't sound like something there'd be a
terrible demand for.

First and foremost, there's the question of how much memory to allocate for
the string. I assume you mean if you have an array such as this:
int a[] = {1, -2033449, 304050, 40};
then you'd want the result to be a string that looks something like this:
"1 -2033449 304050 40"
But how do you determine up front how much memory will be needed? You can
loop through the entire array first, figuring out how long each item plus
seperators will be in text form, add up all the lengths, allocate the
memory, then go back through and do the conversions...of course the lengths
you compute will be based upon how /you/ want the numbers formatted, not
some fixed "standard" format.

If the arrays are short enough that you can get away with a big
fixed-length buffer, you save the first loop and the allocation, but you
still have to control the formatting to suit you.

I think you'll just have to code it as best you can. Look at the bright
side: since you're producing text, it'll probably be destined for some
display or storage device and your program will be mostly I/O bound anyway,
so don't sweat the computation time for the conversion.
-leor


Amittai Aviram


--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #2

"Amittai Aviram" <am*****@amittai.com> wrote in message
news:c4*************@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


Nov 14 '05 #3

"Leor Zolman" <le**@bdsoft.com> wrote in message
news:49********************************@4ax.com...
First and foremost, there's the question of how much memory to allocate for the string. I assume you mean if you have an array such as this:
int a[] = {1, -2033449, 304050, 40};
then you'd want the result to be a string that looks something like this:
"1 -2033449 304050 40"
Yes, that's exactly right. And you're right -- if you don't know from the
outset what your integers will be, you either have to calculate the number
of digits (quite possible but a bit laborious) -- or else you have to assume
an outer bound for decimal digits per element and fudge accordingly, which
is what I've just done.
I think you'll just have to code it as best you can.


I've gone ahead and made a loop using sprintf. Thanks a lot for your
comments.

Amittai

Nov 14 '05 #4

"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:og*****************@newsread2.news.pas.earthl ink.net...
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.


Thank you very much. That was what I meant. I've gone ahead and created
something similar, though yours is, indeed, more elegant.

Amittai

Nov 14 '05 #5
Mac
On Wed, 31 Mar 2004 22:54:47 +0000, Amittai Aviram wrote:

"Leor Zolman" <le**@bdsoft.com> wrote in message
news:49********************************@4ax.com...
First and foremost, there's the question of how much memory to allocate

for
the string. I assume you mean if you have an array such as this:
int a[] = {1, -2033449, 304050, 40};
then you'd want the result to be a string that looks something like this:
"1 -2033449 304050 40"


Yes, that's exactly right. And you're right -- if you don't know from the
outset what your integers will be, you either have to calculate the number
of digits (quite possible but a bit laborious) -- or else you have to assume
an outer bound for decimal digits per element and fudge accordingly, which
is what I've just done.
I think you'll just have to code it as best you can.


I've gone ahead and made a loop using sprintf. Thanks a lot for your
comments.

Amittai


I just want to warn you that most exploits nowadays come from buffer
overflows. Without seeing your exact code, it is hard to say how
vulnerable it might be, but if you intend to distribute it, you should
make sure that a malicious user can't overflow a string buffer by
carefully crafting a strange file or input line.

Just my $0.02

--Mac

Nov 14 '05 #6
"Mike Wahler" <mk******@mkwahler.net> wrote in message
news:og*****************@newsread2.news.pas.earthl ink.net...
#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]);
p += sprintf(p, "%d", array[i]);

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

return 0;
}

Nov 14 '05 #7
Amittai Aviram wrote:

Hi! Is there a convenient way to create a null-terminated string
out of an array of type int? 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, 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!


Try roughly:

char buf[INFINITESIZE];
char *p;

p = buf;
while (whatevercritierionyouneed) {
p += sprintf(p, "format string", item);
}

--
fix (vb.): 1. to paper over, obscure, hide from public view; 2.
to work around, in a way that produces unintended consequences
that are worse than the original problem. Usage: "Windows ME
fixes many of the shortcomings of Windows 98 SE". - Hutchison
Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Mike S. Nowostawsky | last post by:
I tried using the "toUpperCase()" property to change the value of an array entity to uppercase BUT it tells me that the property is invalid. It seems that an array is not considered an object when...
11
by: deko | last post by:
I need to create a basic one-dimensional array of strings, but I don't know how many strings I'm going to have until the code is finished looping. pseudo code: Dim astrMyArray() Do While Not...
4
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where...
11
by: Zordiac | last post by:
How do I dynamically populate a string array? I hope there is something obvious that I'm missing here Option Strict On dim s() as string dim sTmp as string = "test" dim i as integer ...
3
by: Ben | last post by:
Hi I am creating a dynamic function to return a two dimensional array from a delimeted string. The delimited string is like: field1...field2...field3... field1...field2...field3......
5
by: Stacey Levine | last post by:
I have a webservice that I wanted to return an ArrayList..Well the service compiles and runs when I have the output defined as ArrayList, but the WSDL defines the output as an Object so I was...
7
by: Jim Carlock | last post by:
Looking for suggestions on how to handle bad words that might get passed in through $_GET variables. My first thoughts included using str_replace() to strip out such content, but then one ends...
14
by: Peter Hallett | last post by:
I would like to set up a string array as a class member, or field, and then populate this array by reading in from a text file, but I cannot find the appropriate syntax. The getter and setter are...
23
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these...
2
dlite922
by: dlite922 | last post by:
difficult to explain, easier to show: Here's what my data looks like on the PHP side: Array ( => Array ( => 20003001 => ABC RESTAURANT
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.