A simple problem of storing ...

I know , it may be childish question but here it goes :-
I am trying to store value of int variable along with space .
Ex - if a is an int & b is an string , then i am trying to store value of a into b along with a "\n" , ie a new line.
so if a=5 then i want b to be equal to 5\n , ie 5 & then a blank line .
Thanks for help in advanced !
Well, there is a function itoa() for this purpose, but its not ANSI standard, and not always supported by compilers. So, you'll likely want to look into stringstream
Well, that's quite simple and does not need any non-standard functions.
consider this program (C code) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdlib.h>
#include <stdio.h>

int main(int argc,char** argv)
{
printf("Please enter a number : ");
char vsString[255]; // A typed number is not very long, but one could enter anything just for fun (i'm not kidding)
int viNumber = 0; // Always give a default value
scanf("%i",&viNumber);
/*
And here is the magic function. It works like printf, but outputs to a string instead of the console. This string is given as the first argument
See : http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
*/
sprintf(vsString,"%i\n",viNumber);
// The result is now stored in vsString. Let's show it :
printf("%s",vsString);
return EXIT_SUCCESS;
};


As you can see, we just used standard headers, and it works in C !
If you want to use it in C++, you should use the C++ names for the headers : cstdio and cstdlib.
Some compilers now provide safe versions of these functions. I let you use them, as each compiler has it's own set of safe functions, I can't tell you what to use without to know about your compiler (name and version).
Also note that stdlib.h is just used for the return value macro.

I hope that helps you ;)

Jessy V
I would still say stringstream is a safer and simpler way of doing it.
Thankyou ResidentBiscuit & especially Jessy V. , it really works , but i am looking this code for online c++ competition so i myself don't know the compiler name & version (although i know its gnu cpp) . Therefore i am looking for the method that takes the least time and memory .
So if you could provide me a better solution where i do not need to declare any extra header file , it would really really help me.
I have its java version , for showing the example again.
a=a+"\n"; //a is a string
Thus , i think there must be something really simple for this .
Thankyou once again !
Okay , thankyou , i have got it !
Topic archived. No new replies allowed.