need c++ to convert int to string or char *

lopoetve

Extremely [H]
Joined
Oct 11, 2001
Messages
33,902
Ok. Networking tools, have to send a port number to the other computer. This requires (yes, REQUIRES) I convert a number (approx 1000 something) into a string (actually a char *)

IE:

char *thing;
thing = inttostring(BIGNUMBER)
sendto(...)

Does such a thing exist in gcc?
 
You can use sprintf

Code:
#include <cstdio>

int main() {
    int port = 80;
    char* portstring[10];
    
    sprintf(portstring, "%d", port);

    return 0
}

If you only just want to use C++ functions, there's a stream function called strstream that I *think* does the same thing.
 
Int to string:

a stringstream example

Code:
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string int_to_string(const int& port) {
    stringstream ss;
    ss << port;
    return ss.str();
}

int main() {
    int port = 114;
    cout << int_to_string(port) << endl;
}
* used .str() per eloj's example.

a boostlib example (www.boost.org)

Code:
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

int main() {
    int port = 114;
    cout << lexical_cast<string>(port) << endl;
}

lexical_cast<string>() just looks better.
 
I'll post my code tomorrow, but for some reason the method I recieved from someone else works sometimes, but not others... wtf?

I'll show you in the morning... till then, 18hrs of coding is not good for you.

Thanks, I tried sprintf... segfault...
 
It's stringstream. strstream is obsolete.

Code:
template <class T> std::string st(const T& i)
{
  std::ostringstream ss;
  ss << i;
  return ss.str();
}
 
you can use _itoa e.g:

#include <stdlib.h>

int main(void) {
int port=42;
char buff[32];
_itoa(port,buff,10);
}
 
BenM said:
you can use _itoa e.g:

#include <stdlib.h>

int main(void) {
int port=42;
char buff[32];
_itoa(port,buff,10);
}

I've never gotten that to work. Is that just in Microsoft Visual C++? That's the only place I've seen it...
 
lopoetve said:
I've never gotten that to work. Is that just in Microsoft Visual C++? That's the only place I've seen it...

I'm nearly 100% sure I've used it in C/C++ coding before using gcc 3.3+ in Linux.
 
It works with gcc 3.4.1 on windows (MinGW)
(Of course this method is more C than C++. Plus itoa() is not part of the standard)

Code:
#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
    int port = 42;
    char buff[32];
    itoa(port,buff,10);
    cout << buff << endl;
}
 
Oops, I think I made a mistake. In my code, you should not have the [] when defining the char pointer.

Code:
#include <cstdio>

int main() {
    int port = 80;
    char* portstring;
    
    sprintf(portstring, "%d", port);

    return 0;
}

That's what being up at 3 in the morning will do for you.

The code works for me. And yeah, itoa is not a standard C function.
 
BillLeeLee said:
Oops, I think I made a mistake. In my code, you should not have the [] when defining the char pointer.

Code:
#include <cstdio>

int main() {
    int port = 80;
    char* portstring;
    
    sprintf(portstring, "%d", port);

    return 0;
}

That's what being up at 3 in the morning will do for you.

The code works for me. And yeah, itoa is not a standard C function.


you need to either have:
char *portstring=new char[some size]
or
char portstring[some size]

otherwise its printing into uninitialised memory, which might work some times, but crash others.

itoa() is pretty standard, just for some reason microsoft has appended a '_' to the front of it, when in linux its just itoa(). Theres lots of useful ones with the appended '_', like _snprintf() which you should probably use instead of sprintf().
 
eloj said:
It's stringstream. strstream is obsolete.

Code:
template <class T> std::string st(const T& i)
{
  std::ostringstream ss;
  ss << i;
  return ss.str();
}

I don't know anything about using templates. :(
 
lopoetve said:
Um, itoa doesn't exist. Sorry

I use it all the time:

http://msdn.microsoft.com/library/d...i64toa.2c_._itow.2c_._i64tow.2c_._ui64tow.asp

and

http://www.cplusplus.com/ref/cstdlib/itoa.html

the second link says its not defined in ANSI-C , but I've never had any problems with it with MSVC in windows or gcc in linux (and after a quick look it seems to be supported by the borland libraries aswell).

If you havent found something else that works, have another go with this.
 
BenM said:
I use it all the time:

http://msdn.microsoft.com/library/d...i64toa.2c_._itow.2c_._i64tow.2c_._ui64tow.asp

and

http://www.cplusplus.com/ref/cstdlib/itoa.html

the second link says its not defined in ANSI-C , but I've never had any problems with it with MSVC in windows or gcc in linux (and after a quick look it seems to be supported by the borland libraries aswell).

If you havent found something else that works, have another go with this.

Running gcc with Linux, included stdlib.h, and it can't find it.
:(
 
> included stdlib.h,

You should #include <cstdlib>, not <stdlib.h>, and then make sure you're looking in the correct namespace.

I suggest you try the template code I gave you. Just put it in your code and use it as a function.

if (st(-10405060) == "-10405060" ) { // success! }
 
lopoetve said:
Running gcc with Linux, included stdlib.h, and it can't find it.
:(

strange, I just got off my lazy arse and found a linux machine to try it on, and its gone, I dont know when that happened. I better get used to doing it the other ways, it was a useful function. ah well, looks like you'll have to use that template, or sprintf, which is definately there.
 
eloj said:
> included stdlib.h,

You should #include <cstdlib>, not <stdlib.h>, and then make sure you're looking in the correct namespace.

I suggest you try the template code I gave you. Just put it in your code and use it as a function.

if (st(-10405060) == "-10405060" ) { // success! }

I've never used templates before, and I don't know where to start. Anyway, I got it working. Stole it from the old stdlib, and it works now

Thanks all!
 
I like to do it the old fasion way, b/c it keeps me on top of my mad programming skills :D

anyway, here is a function (tested and true) that I wrote in responce to this thread:

Code:
// changes an int to a char *
// returns an address to a character array and
//    returns the length of the array
char * numtochar(int num, int &length)
{
	int temp = num;
	int counter = 0;
	bool IsNegative = false;

	// test if negative
	if(num<0)
	{
		counter++;
		IsNegative = true;
	}


	// find the length of the number
	while(temp != 0)
	{
		temp /= 10;
		counter++;
	}

	length = counter;

	char * String = new char[counter];

	// fill the char array
	for(int i=counter-1; i>=0; i--)
	{
		temp = num%10;

		if(IsNegative == true)
			temp *= -1;

		switch(temp)
		{
			case 0: String[i] = '0'; break;
			case 1: String[i] = '1'; break;
			case 2: String[i] = '2'; break;
			case 3: String[i] = '3'; break;
			case 4: String[i] = '4'; break;
			case 5: String[i] = '5'; break;
			case 6: String[i] = '6'; break;
			case 7: String[i] = '7'; break;
			case 8: String[i] = '8'; break;
			case 9: String[i] = '9'; break;
			default: String[i] = 'n'; break;
		}

		num /= 10;
	}

	if(IsNegative==true)
		String[0] = '-';

	return(String);
}

I hope it helps

BTW: since it is using a pointer, you have to delete the memory outside of the function.
 
I believe itoa was taken out of newer gcc versions because for one thing, it's not defined in the ANSI C standard. GCC is aimed towards portability and standards compliancy, so in newer versions, they took itoa out. Useful yes, but it can be done in other ways (though might not be as easy to do).

I still can't get an explanation as to why GCC does not support the 'extern' keyword for C++ (though Herb Sutter has written an essay about why extern is bad).

Anyway, a quick templates tutorial so you can use them in the future, because they are an excellent part of C++ that is not as widely used as they should be (very very useful for generic programming). :D

Code:
template <typename T> T max(T &var1, T &var2)
{
return (var1>var2) ? var1 : var2;
}

Very common example is the max function.

This is a template function (there are template classes, usually used for algorithms that apply to many data types, and common data structures. The C++ STL is all about generic template).

Template functions start with the keyword 'template' followed by <typename T>.
The typename means a data type of T, whatever it may be (int, double, float, a user defined data type).

So when I say "T max(T &a, T &b)" I mean the function max accepts two variables of some data type, and returns something of that data type.

Here's the template code in use.

Code:
#include <iostream>
using std::cout;
using std::endl;

template <typename T>
T max(T &a, T &b);

int main()
{
int a = 100;
int b = 50;

cout << max(a, b) << endl;

return 0;
}

template <typename T>
T max(T &a, T &b)
{
return (a > b) ? a : b);
}

Really basic example, there's a lot more to templates (like specialization and class templates and what not) but this is a good start, I suppose. It's how I started with templates.

I'm pretty sure what I just wrote works. I'm in between classes so time to go.

Oh, and BenM, thanks for the fix of my code. Just need to put that delete[] pointer in there if char* is being allocated with new. Of course, if he wasn't doing c++, we'd have to use malloc and free, yuck.
 
Here another cute template example.

Code:
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
#include <vector>

using namespace std;

template <class T> string to_str(const T& i) {
    ostringstream ss;
    ss << i;
    return ss.str();
}

int main() {
    vector<int> vt;
    vt.push_back(99);
    cout << to_str(vt.at(0)) << endl;
    char* test = "25";
    cout << to_str(test) << endl;
    char arr[4] = "114";
    cout << to_str(arr) << endl;
    cout << to_str('4') << endl;
    cout << to_str(8080) << endl;
    cout << to_str(bitset<32>(35)) << endl;
    cout << to_str(1115.23) << endl;
    cout << to_str("blah blah blah") << endl;
}

Using a template, you can pass different data types to the function to convert them to a string. That way you are not limited to one type. So the function becomes whateverToString() instead of just intToString().
 
Shadow2531 said:
Here another cute template example.

Code:
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
#include <vector>

using namespace std;

template <class T> string to_str(const T& i) {
    ostringstream ss;
    ss << i;
    return ss.str();
}

int main() {
    vector<int> vt;
    vt.push_back(99);
    cout << to_str(vt.at(0)) << endl;
    char* test = "25";
    cout << to_str(test) << endl;
    char arr[4] = "114";
    cout << to_str(arr) << endl;
    cout << to_str('4') << endl;
    cout << to_str(8080) << endl;
    cout << to_str(bitset<32>(35)) << endl;
    cout << to_str(1115.23) << endl;
    cout << to_str("blah blah blah") << endl;
}

Using a template, you can pass different data types to the function to convert them to a string. That way you are not limited to one type. So the function becomes whateverToString() instead of just intToString().

Sweet llama of God! :D
 
By Stroustrup's beard, this is 2004 not 1992, the time for manually converting int-to-string or string-to-int is long long long over, as is returning a naked pointer to dynamically allocated memory (with an implied transfer of ownership).

boost::lexical_cast, for simple uses like the one described
boost::format, for more control over formatting options (akin to sprintf)
 
Virus2566 said:
I like to do it the old fasion way, b/c it keeps me on top of my mad programming skills :D

anyway, here is a function (tested and true) that I wrote in responce to this thread:

(snip code)

I hope it helps

BTW: since it is using a pointer, you have to delete the memory outside of the function.

Actually, you'll need to delete[] the memory, but you should skip this type of solution entirely, unless you're writing it purely to have written such a function. If you're stuck with C, then sprintf will be a better solution, in C++, there are many better solutions.
 
Back
Top