Conversion Made Easy?!

Light Poster
1Jan2007,21:59   #1
danielakkerman's Avatar
Hello,
Recently, After resolving major issues thanks to your patience and help, I've encountered another problem:
Code:
int x = 123;
Now, I am aware of the method to covert int to char(array):
Code:
int x = 123;
char y[25];
sprintf(y, "%d", x);
Here's the problem:
I need to concatenate x to y(place x at the END of y), which something that I was able to accomplish since 'sprintf' basically overwrites whatever was previously stored in y.
Any suggestions?
Thanks again,
Thanks,
Daniel
Team Leader
1Jan2007,23:34   #2
DaWei's Avatar
Here's how this works:
I want to convert a number to a string.
I want to convert a number to a string and concatenate it to another string.
What do I need to know?
a) How to convert a number to a string.
b) How to concatenate two strings.
What do I know?
a) How to convert a number to a string.
What do I need to know?
a) How to concatenate two strings.

Once you know these two things, the job can be done. First pass, you'll probably make two strings, convert two numbers, and concatenate the second string to the first. Second pass, you'll look at your code and ask yourself how to simplify it. When you realize that a pointer to a string is simply a pointer to the first element of the string, and that a pointer can point at any element, thanks to pointer arithmetic, then you're home free.

Notice that I don't need int y if I'm willing to lose int x. I can simply replace int x with the new value at the appropriate point in the process. Further, I don't need either int if I can get away with putting the literal value directly in the sprintf statement. What you will need is knowledge of your circumstances, which will vary from case to case. This is part of the design phase, which always comes before you sit down at the keyboard.
Code:
#include <stdio.h>

int main (void)
{
	int x = 123;
	int y = 456;
	char theCombo [256];
	sprintf (theCombo,"%d", x);
	printf ("First step: %s\n", theCombo);
	sprintf (theCombo + strlen (theCombo), "%d", y);
	printf ("Second step: %s\n", theCombo);
	return 0;
}
Quote:
Originally Posted by Output
First step: 123
Second step: 123456
Light Poster
2Jan2007,19:01   #3
danielakkerman's Avatar
Hi,
It's finally working, Thanks.
Daniel
Go4Expert Founder
2Jan2007,19:06   #4
shabbir's Avatar
I can give a try on one more way but it should be a similar to DaWei but in less steps

sprintf(y, "%s%d",y,x);

It will append the x to y but I have not executed it but there can be an issue with \0 of the previous content of y and you can try and see what is the output.
Team Leader
2Jan2007,22:06   #5
DaWei's Avatar
Good idea. "sprintf (y, "%s%d", y, x);" will definitely work the same as "sprintf (y + strlen (y), "%d",x);". Since sprintf is set up to concatenate, it'll handle the '\0' just fine.