Sign in to follow this  
prophete

how do i concatenate a string with an integer?

Recommended Posts

One possible way, there are much better and safer ways :)

Look at sprintf and snprintf


sprintf(buffer, "%s%d", myString, myInt);


So if myString is "Hello" and myInt is 5, buffer will now be "Hello5". Dangers of this inluding not having large enough space in buffer variable but you can calculate max size.

Share this post


Link to post
Share on other sites
In c, you can sprintf() the integer to the string, like so ( forgive me if this isnt perfect, I dont usually use c )



char *buffer = /*some c string */;
sprintf(buffer + strlen(buffer),"%d",i);



The strlen(buffer) is to make sure it adds it to the end of the string.

Share this post


Link to post
Share on other sites
Quote:
Original post by prophete
i tried

char *toReturn[4];
sprintf(toReturn[3] + strlen(toReturn[3]), "%d", result);

it's giving me a runtime error..
You haven't allocated the buffer, so you'll get an access violation.

Try:

char toReturn[4][256];
strcpy(toReturn[3], "Some string");
sprintf(toReturn[3] + strlen(toReturn[3]), "%d", result);




Or, better, switch to C++ and use std::string and std::stringstream.


EDIT: Woooah, I hope you're not trying to return these pointers from a function, are you? If so, you'll need to use malloc() to allocate memory for them, since if they're on the stack they'll be destroyed when the function exits.

Share this post


Link to post
Share on other sites
Quote:
Original post by prophete
yeah i wanted to return the array toReturn ..
thanks steve that worked, but what was the 256 for?


Evil Steves code creates an array of 4 256 character strings. Did you just want a 4 character long string?

If you were going to return an array, you should probably re-write it to something like this:


void appendInt( char *str, int val )
{
sprintf(str+ strlen(str),"%d",val);
}


and call it like so:


char str[100] = "The value of i is ";
appendInt(str,i);

Share this post


Link to post
Share on other sites
C strings are pointers to storage. They are not garbage collected or reference counted.

This means you have to allocate and deal with storage for every character you deal with.

As an exception, "static" strings in quotes are allocated by the compiler.

But any other string you build, you have to manage the lifetime of the memory, the amount of memory, and what character goes into what part of memory.

rip-off's posts will result in memory corruption.

....

I would advise against dealing with raw C strings. Try the following:


typedef struct Buffer {
char* start;
char* end;
} Buffer;

Buffer allocate_buffer( size_t n ) {
char* tmp = calloc( n, sizeof(char) );
Buffer result = {tmp, tmp+n};
return result;
}

void dispose_buffer( Buffer b ) {
free( b.begin );
}


The Buffer struct stores both the start pointer to a block of memory, and the size of the block of memory.

Using it, and some care, you can avoid corrupting memory. Because you actually know how large your memory allocations are. :)

And then you can write buffer-overrun-safe string modification functions:

// returns non-zero on success, 0 on error.
int append_string( Buffer b, char* str ) {
size_t n = strlen(str);
size_t b_n = strlen(b.begin);
if (b_n + n + 1 > (b.end-b.begin)) return 0; // error!
sprintf( b.begin+b_n, "%s", str );
};

int append_int(Buffer b, int i ) {
char tmp[100];
sprintf(tmp, "%d", i);
return append_string( b, tmp );
}


C is a very low level language. You are directly dealing with the stack, heap, and the processor. You should think of C as a fancy assembler rather than the kinds of languages you have delt with before.

Now, note that in C++, I would do it very differently.

Share this post


Link to post
Share on other sites
Quote:

rip-off's posts will result in memory corruption.


I'm sorry, but how? [smile]

Granted the function requires that the buffer has enough space to handle the extra characters being appended (which I should have checked [embarrass]), but once that has been met how would there be memory corruption?

I know if the string is not NUL terminated it could cause problems, but its a c-string, if they dont aren't NUL terminated you don't have much hope anyway.

I do agree with you BTW, but I really feel if you are willing to go to those lengths you would be much better off jumping to c++ anyway, unless there is some real restriction thats keeping you using c.

Share this post


Link to post
Share on other sites
Quote:
Original post by rip-off
Quote:

rip-off's posts will result in memory corruption.


I'm sorry, but how? [smile]

Granted the function requires that the buffer has enough space to handle the extra characters being appended (which I should have checked [embarrass]), but once that has been met how would there be memory corruption?


That would be the problem that's alluded to.

Note that 'char* buffer = /* some C string */' doesn't suggest anything about checking buffer size. The point is, you *have* to "own" memory following the string that is big enough to hold the text representation of the number, and it *has* to not be in use for something else already.

Share this post


Link to post
Share on other sites
Quote:
Original post by Zahlman
Quote:
Original post by rip-off
Quote:

rip-off's posts will result in memory corruption.


I'm sorry, but how? [smile]

Granted the function requires that the buffer has enough space to handle the extra characters being appended (which I should have checked [embarrass]), but once that has been met how would there be memory corruption?


That would be the problem that's alluded to.

Note that 'char* buffer = /* some C string */' doesn't suggest anything about checking buffer size. The point is, you *have* to "own" memory following the string that is big enough to hold the text representation of the number, and it *has* to not be in use for something else already.


Oh, ok, I though NotAYakk was implying that it currently ( even with most of the size 100 example buffer empty ) was causing memory corruption, not that it had the possibility of memory corruption if misused( which I was aware of ), if you know what I mean.

I should have thought more of your signature, really.


Share this post


Link to post
Share on other sites
How will your posts cause memory corruption?

They will cause memory corruption in two ways. Both in the particular and in the abstract.


char *buffer = /*some c string */;
sprintf(buffer + strlen(buffer),"%d",i);


No length checking is done above -- so in the particular, you have memory corruption above. There are c strings that will cause the above chunk of code execute undefined behaviour.

...

In the abstract, if you don't keep the eye on the ball -- keep track of the length of every c string you append data to -- you will cause memory corruption in a project.

You'll even usually get lucky -- memory will be allocated with room between one chunk of memory and the next, and most of the time you will have enough room. Quite often because "common memory corruption" gets weeded out as the application crashes.

But the more you work with blocks of memory without always keeping track of their length, the more memory corruption you will have.

So never ever ever make any string longer if you don't know how long it is. Always check to see if the buffer you are modifying will have enough room to store the string you want to store there.

I find the best way to deal with never and always commandments is to touch your data only with functions (ADT), and don't manipulate the data directly.

Hence the Buffer struct, and the functions I provided that start off manipulating them.

Share this post


Link to post
Share on other sites
Quote:
Original post by NotAYakk
How will your posts cause memory corruption?


Aww, I was expecting the answer "by introducing the risk that the OP would remember a dangerous way of doing things" ('remember' being the operative word). :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this