value from integer variable to string variable

I want to assign the value from an integer variable to a string variable. If there integer variable had 1111 I want the string variable to have 1111 also. This is what I tried(in comment is the 2nd thing I tried):
1
2
3
4
  int result = 1111;
  string binary = "";
  binary = static_cast<unsigned char>(result);
 //binary.insert(0,static_cast<unsigned int>(result)); 
That wont work. There are a few ways of doing this, but the eaisest way is to use std::to_string (you'll need a C++11 compatible compiler to do this, but don't worry - you should):
1
2
3
4
int result = 1111;
std::string binary = std::to_string(result);

std::cout << binary;  // prints '1111' 
Last edited on
Hi,
I know this
way;

regards!

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
//intToString.cpp
//##

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

using namespace std;

int main(){



        int result=1111;
        string someString;

        ostringstream os;
        os<<result;

        someString=os.str();

        cout<<someString<<endl;

return 0; //indicates success
}//end of main
1111
closed account (z1CpDjzh)
This should work.


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
33
34
35
36
37
38
//intToString.cpp
//##

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

int main(){


		 //Geting value of result
        int I_RES;
		std::string Imput;

		std::cout << "Please Imput your Number... \n Imput: ";
		std::getline(std::cin, Imput);
		std::cout << "... \n The varible has been stored as a string... \n"
				  << "Coverting to Int... \n";

        std::stringstream SS1;
        SS1 << Imput;
		SS1 >> I_RES;

		std::cout << "Converting Integer Back to String... \n";

		//Int to string
		std::string S_RES;
		std::stringstream SS2;
		SS2 << I_RES;
		SS2 >> S_RES;

		//Printing it out
		std::cout << " The string = " << S_RES;

		//Puasing program
		std::cin.get();
return 0; //indicates success
}//end of main 

Please Imput your Number...
 Imput: 999
...
 The varible has been stored as a string... 
Coverting to Int... 
Converting Integer Back to String... 
The string = 999
Please Imput your Number...
 Imput: 1111
...
 The varible has been stored as a string... 
Coverting to Int... 
Converting Integer Back to String... 
The string = 1111
Please Imput your Number...
 Imput: 1000
...
 The varible has been stored as a string... 
Coverting to Int... 
Converting Integer Back to String... 
The string = 1000


PS: Sorry if its to complicated for your brain to handle :p
-TheGentlmen
Last edited on
Than you guys @NT3 @eyenrique @TheGentlmen (even though "if its to complicated my your brain to handle"), your suggestions realy helped.
Topic archived. No new replies allowed.