| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
How to add an int to a std::string???
Say I have a string object and I want to add an integer to it, how would I do it?
Code:
#include <string>
#include <iostream>
using namespace std;
int main() {
int value = 5;
string s;
s = "The value is: ";
s += value;
cout << s << endl;
return 0;
}
I'd like it to output, "The value is: 5" -- however all it outputs is "The value is: ". Please help.. this simple problem is driving me nucking futs. |
|
#2
|
||||
|
||||
|
I'm not sure if this is standard C++, but in C you can use the sprintff() function, ie:
sprintf(s,"%d",value) if you're familiar with printf() that should make sense ![]() |
|
#3
|
|||
|
|||
|
doesn't compile. I'm using C++ and its the GNU compiler (i think)
|
|
#4
|
|||
|
|||
|
Nevermind, I finally figured it out
A. Converting from int to string is a little more complicated than converting a string to int. There are no standard C++ functions for this, but there is a way to do it using standard stringstreams. The class stringstream is declared in header sstream and is used like this: std::stringstream ss; std::string str; ss << 31337; ss >> str; |
|
#5
|
||||
|
||||
|
Quote:
actually, it would probably be fairly easy to manually convert an int to a string... you'd just need to set a loop and devide your int by different powers of 10, logging your results as you go..... but then, that would be the "interesting" way of dong it ![]() |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > How to add an int to a std::string??? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|