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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert int to string

Status
Not open for further replies.

ARCITS

Programmer
Apr 4, 2002
99
GB
I have an int s and want to convert this to string s.
How?

Thanks
 
You can't convert an integer to string the only thing you can do is to "insert" it in.

CString str;
int s;
str.Format("%d", s);
 
yes it is possible to convert an integer to a string.
you can do it by using this fonction:
char *_itoa( int value, char *string, int radix )

an example:

#include<stdlib.h>
#include<iostream.h>
void main()
{
char buffer[20];
int number = 7254;
cout<<&quot;buffer = &quot;<<_itoa( number, buffer, 10 );
}
// notice that the last parameter of that fonction neads to be equal to 10 if you want your number to be stored as a decimal value.By choosing 2 as the last parameter would convert your number to binary etc.


 
Impress your friends and colleagues.

If you want to use a fancy pure C++ construct, you can do this:

#include <iostream>
#include <sstream>
#include <string>

int intFromString(const std::string& s)
{
std::istringstream i(s);
int x;
if (i >> x)
return x;
// error handling goes here...
return 0;
}

You can write a custom handler for all data types and then you will never face the problem again.
 
Ooops I gave you string to int, which isn't what you wanted. Of course the solution is similar, again using the fancy pure C++ constructs:

#include <iostream>
#include <sstream>
#include <string>

std::string convertToString(int x)
{
std::eek:stringstream o;
if (o << x)
return o.str();

// error handling
return &quot;conversion error&quot;;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top