By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,978 Members | 1,831 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,978 IT Pros & Developers. It's quick & easy.

Converting Numbers to Strings

P: 3
I am very new to C++ and I am trying to figure out how to convert a number to a string (even in the simplest case such as
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <sstream>
  3. using namespace std;
  4.  
  5. int main () {
  6.   int a;
  7.   a = 1;
  8.   b = 2;
  9.  
  10.   string c;
  11.   c = ?????????????????????
  12.     cout << c;
  13.  
  14.  
  15.   return 0;
  16. }
  17.  
What do I put where the question marks are??? How would I convert a and b into strings and then concatenate them??

Thanks for your help
Jul 5 '07 #1
Share this Question
Share on Google+
4 Replies


sicarie
Expert Mod 2.5K+
P: 4,677
Have a look at this.

(And please use code tags! Thanks!)
Jul 5 '07 #2

archonmagnus
100+
P: 113
Since it looks like you are dealing with integers, you might want to investigate the atoi function as well.

C++ "atoi" Reference Page
Jul 5 '07 #3

weaknessforcats
Expert Mod 5K+
P: 9,197
atoi is a deprecated function in C++.

You should use a stringstream:
Expand|Select|Wrap|Line Numbers
  1. int val = 123;
  2. string str;
  3. stringstream ss;
  4. ss << val;
  5. ss >> str;
  6.  
  7. cout << str << endl;
  8.  
Here the integer is inserted in the stringstream as the characters 1 2 3. Then the characters are extracted from the stringstream into your string object.
Jul 6 '07 #4

10K+
P: 13,264
atoi is a deprecated function in C++.

You should use a stringstream:
Expand|Select|Wrap|Line Numbers
  1. int val = 123;
  2. string str;
  3. stringstream ss;
  4. ss << val;
  5. ss >> str;
  6.  
  7. cout << str << endl;
  8.  
Here the integer is inserted in the stringstream as the characters 1 2 3. Then the characters are extracted from the stringstream into your string object.
You'll notice that the OP had actually included sstream!
Jul 6 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.