Solved

How could I convert integer to string?

Posted on 2011-03-02
477 Views
Dear,

What is the function used to convert integer to string in C/C++?

currently, in delphi we have inttostr function.

Nabil.
0
Question by:nabilhammoud

LVL 44

Expert Comment

ID: 35024590
itoa and ltoa (and variants for wide strings).
0

LVL 40

Accepted Solution

evilrix earned 125 total points
ID: 35024710
EE's very own DanRollins has written a good article on this very subject...

"Convert String to int / Convert int to String in C++"
http://www.experts-exchange.com/Programming/Languages/CPP/A_1577-Convert-String-to-int-Convert-int-to-String-in-C.html
0

LVL 32

Assisted Solution

phoffric earned 125 total points
ID: 35024718
itoa may or may not be part of your system as it is not in the standard library. If you wish to do this in C++, here is an example that shows how to do it.
http://www.cplusplus.com/reference/iostream/istringstream/istringstream/
``````// using istringstream constructors.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main () {

int n,val;
string stringvalues;

stringvalues = "125 320 512 750 333";
istringstream iss (stringvalues,istringstream::in);

for (n=0; n<5; n++)
{
iss >> val;
cout << val*2 << endl;
}

return 0;
}
``````
0

LVL 32

Expert Comment

ID: 35025725
the sample phoffric provided converts string to integer. you need to use ostringstream for the reverse conversion:

std::ostringstream oss;
int i = 12345;
oss << i;
std::string si = oss.str();

if you need char array the last statement turns to

const char * pcs = oss.str().c_str();

Sara
0

Expert Comment

ID: 35025776
int val = 10;
char buff[10];

printf("value: %s\n", buff);

//prints value: 10
0

Author Closing Comment

ID: 35025910
THX
0

Featured Post

Suggested Solutions

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.