How do you pass an integer to a string?

I'm wondering what are some other ways to pass an integer to a string.
I know of using the stringstream function from the header file <sstream> but when I do use it, there are conflicts when using functions from the header file <string>. When I use functions from "#include <string>" the program tries to search through it from sstream and not from the string header file.

So yeah, I was wondering what are other ways I can turn an integer into a string.
I know of using the stringstream function from the header file <sstream> but when I do use it, there are conflicts when using functions from the header file <string>. When I use functions from "#include <string>" the program tries to search through it from sstream and not from the string header file.

Huh? What do you mean?

So yeah, I was wondering what are other ways I can turn an integer into a string.

A better way is to use lexical_cast. See this post:
http://www.cplusplus.com/forum/beginner/46903/#msg254781
I'm wondering what are some other ways to pass an integer to a string.
I know of using the stringstream function from the header file <sstream> but when I do use it, there are conflicts when using functions from the header file <string>. When I use functions from "#include <string>" the program tries to search through it from sstream and not from the string header file.


Get a better compiler or show your code because this should not happen.
Nevermind I figured what was wrong. I didn't include this one thing that I thought I wasn't needed
1
2
3
4
  stringstream input_to_string;
  input_to_string << input;
    
  int input_length(input_to_string.str().length());


I originally had it without the ".str()" when trying to figure out the length of the string. I didn't know I had to include it.


Just for fun I'm posting another method that is a little more versatile in that it allows formatting in the spirit of printf() ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Standard Library includes

#include <iostream>
#include <cstdarg>
#include <string>

using namespace std;

//___________________________________________________________
// Format and return a string in the spirit of sprintf().

string FormatString(const char *spFormat, ...)
{
	va_list argsList;
	char tmpBuf[2048];

	va_start(argsList, spFormat);
	vsprintf(tmpBuf, spFormat, argsList);
	va_end(argsList);

	return string(tmpBuf);
}

//___________________________________________________________
// Example
{
      // ...
      double x(32.12), y(88.23), z(9.21);
      string tmp = FormatString("Coordinate : (%12.4f, %12.4f, %12.4f)",x,y,z);
      cerr << tmp << endl;
}

Last edited on
Topic archived. No new replies allowed.