C M S C     2 1 4
C o m p u t e r   S c i e n c e   I I
F a l l   2 0 0 2


Converting Numbers to Strings

Updated Sept. 23. 2002

Introduction

Strings are very useful in programming languages. So useful that you often want to convert things to strings, or to parse the string using operations that you would normally find in stream operators (such as cin).

One problem with strings is that it's not easy to convert numbers to strings. In Java, you can simply to "" + num where num is some number, and it knows how to convert the number to a string.

One particularly neat way to do this conversion is to use string streams. Here's how to work with output string streams.

You may wish to read about other string operations in the C++ string library, as well as how to work with input string streams. Learning new methods on existing libraries lets you make the full use of the library. Often, students unfamiliar with libraries don't take advantage of what's being offered.

Here's an example:

#include <iostream>
#include <sstream>

using namespace std ;

int main()
{
  ostringstream sout ;

  // Puts a number into the ostrstream
  sout << 124 ;

  // Extracts string from the stream, which is the string 124.
  string s = sout.str() ;

  // Prints "124" (no quotes)
  cout << s << endl ;  
}
You may need to clear the string stream after removing the value.

Note: The library, <sstream>, has now replaced the deprecated (i.e., older version) <strstream> library.

Similarly, use ostringstream, istringstream, and stringstream, instead of ostrstream, istrstream, and strstream.

Web Accessibility


See the class syllabus for policies concerning email
Last Modified: Fri Sep 13 20:11:45 EDT 2002
left up down right home

Web Accessibility