10/07/2009

C++: How to Add or Convert a Number to a String

Concatenate, Append or Attach an Integer, Int, Double, Numeric Value to a Literal String

In some languages, the ability to attach a number to a string is simple. For example, in PHP, string and numeric values are almost completely interchangeable:
<?php


$someNumber = $number1 + $number2;
$outputString = "I calculate that $number1 and $number2 is going to be $someNumber\n";


?>

But with C++ there are some extra steps you need to go through. Apparently, C++ uses "streams" to direct output -- cout being the most used example.

One way to achieve this is to use the following technique:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main () {
int someNumber = 0;
string someString = "";

// GET AN INTEGER
cout << "Enter a small integer: ";
cin >> someNumber;

// CREATE FIRST STREAM NAMED numberAsString
std::ostringstream numberAsString;
numberAsString << someNumber;

// CREATE SECOND STREAM NAMED gatheredString
std::ostringstream gatheredString;

someString = "Thanks, here's some information about your number:\n\n";

// START ADDING TO THE SECOND STREAM
gatheredString << someString;

// ADD THE FIRST STREAM IN THE SECOND STREAM
gatheredString << "Your integer was: " << numberAsString.str() << "\n\n";

// ADD SOME NUMERIC VALUES TO THE SECOND STREAM
gatheredString << "Your integer added to itself is: " << (someNumber + someNumber) << "\n\n";
gatheredString << "Your integer squared is: " << (someNumber * someNumber) << "\n\n";

// OUTPUT THE SECOND STREAM TO THE SCREEN
cout << gatheredString.str();

return 0;
}

No comments :

Post a Comment