Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how can i convert an integer to string ?

Status
Not open for further replies.

satellite03

IS-IT--Management
Dec 26, 2003
248
IN
how do i convert an integer to a string ?

say,
int x = 1234;

how do i get a string from it (i.e string s = "1234") ?

how can i do it ?
 
CString stri;
int i;
i=1234;
stri.Format("%d",i);

then stri will be "1234
 
Code:
string s = "1234";
int mynum = 0;

mynum = atoi(s.c_str());

// Now mynum is 1234

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
hi, r u sure your code is giving result ? i am getting compile error.

Code:
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
          
int main()
{       

CString stri;
int i;
i=1234;
stri.Format("%d",i);
cout<<stri<<endl; // show the string
    
for(int k=0;k<stri.length();k++)
cout<<stri[k]<<endl;//show each character 
}


it is giving compile error... do i need any other header.
 
kaya17's example uses the MFC string class called CString. Skute's example converted a string to an integer. chipperMDW's FAQ should be very helpful, but I didn't see an example. So here goes:
Code:
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    int i = 1000;
    std::ostringstream theStream;
    theStream << i << " + " << 234 << " = " << i+234;

    std::string theString = theStream.str();
    std::cout << theString << std::endl; // show the string

    for (std::string::size_type k = 0; k < theString.length(); k++)
        std::cout << theString[k] << std::endl;//show each character 
}
 
hi uolj, yes, exactly, it is working.

hi, can i do it in C ? C has a function itoa(). but this is non-standard. what does it mean non-standard? does it mean all compiler does not support it ?

anyway,if i leave itoa() ..is there any smart portable solution in C ?
 
Standard way to go:
Code:
#include <cstdio>
char image[16];
int intvar = 1234;
sprintf(image,"%d",intvar);
Include <stdio.h> in C...
 
You can use the stringstream class

#include <stringstream>

int i=100;
stringstream ss;

ss << i;

To access the string from the stringstream,
cout << ss.str() << endl;

To acccess a C-string,
cout << ss.str.c_str() << endl;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top