Search

17.2 — std::string construction and destruction

In this lesson, we’ll take a look at how to construct objects of std::string, as well as how to create strings from numbers and vice-versa.

String construction

The string classes have a number of constructors that can be used to create strings. We’ll take a look at each of them here.

Note: string::size_type resolves to size_t, which is the same unsigned integral type that is returned by the sizeof operator. It’s actual size varies depending on environment. For purposes of this tutorial, envision it as an unsigned int.

string::string()

  • This is the default constructor. It creates an empty string.

Sample code:

Output:


string::string(const string& strString)

  • This is the copy constructor. This constructor creates a new string as a copy of strString.

Sample code:

Output:

my string

string::string(const string& strString, size_type unIndex)
string::string(const string& strString, size_type unIndex, size_type unLength)

  • This constructor creates a new string that contains at most unLength characters from strString, starting with index unIndex. If a NULL is encountered, the string copy will end, even if unLength has not been reached.
  • If no unLength is supplied, all characters starting from unIndex will be used.
  • If unIndex is larger than the size of the string, the out_of_range exception will be thrown.

Sample code:

Output:

string
stri

string::string(const char *szCString)

  • This constructor creates a new string from the C-style string szCString, up to but not including the NULL terminator.
  • If the resulting size exceeds the maximum string length, the length_error exception will be thrown.
  • Warning: szCString must not be NULL.

Sample code:

Output:

my string

string::string(const char *szCString, size_type unLength)

  • This constructor creates a new string from the first unLength chars from the C-style string szCString.
  • If the resulting size exceeds the maximum string length, the length_error exception will be thrown.
  • Warning: For this function only, NULLs are not treated as end-of-string characters in szCString! This means it is possible to read off the end of your string if unLength is too big. Be careful not to overflow your string buffer!

Sample code:

Output:

my s

string::string(size_type nNum, char chChar)

  • This constructor creates a new string initialized by nNum occurances of the character chChar.
  • If the resulting size exceeds the maximum string length, the length_error exception will be thrown.

Sample code:

Output:

QQQQ

template<class InputIterator> string::string(InputIterator itBeg, InputIterator itEnd)

  • This constructor creates a new string initialized by the characters of range [itBeg, itEnd).
  • If the resulting size exceeds the maximum string length, the length_error exception will be thrown.

No sample code for this one. It’s obscure enough you’ll probably never use it.

string::~string()

String construction

  • This is the destructor. It destroys the string and frees the memory.

No sample code here either since the destructor isn’t called explicitly.

Constructing strings from numbers

One notable omission in the std::string class is the lack of ability to create strings from numbers. For example:

Produces the following error:

c:vcprojectstest2test2test.cpp(10) : error C2664: 'std::basic_string<_Elem,_Traits,_Ax>::basic_string(std::basic_string<_Elem,_Traits,_Ax>::_Has_debug_it)' : cannot convert parameter 1 from 'int' to 'std::basic_string<_Elem,_Traits,_Ax>::_Has_debug_it'

Remember what I said about the string classes producing horrible looking errors? The relevant bit of information here is:

cannot convert parameter 1 from 'int' to 'std::basic_string

In other words, it tried to convert your int into a string but failed.

The easiest way to convert numbers into strings is to involve the std::ostringstream class. std::ostringstream is already set up to accept input from a variety of sources, including characters, numbers, strings, etc… It is also capable of outputting strings (either via the extraction operator>>, or via the str() function). For more information on std::ostringstream, see Lesson 13.4 -- Stream classes for strings.

Here’s a simple solution for creating std::string from various types of inputs:

Here’s some sample code to test it:

And the output:

4
6.7
A

Note that this solution omits any error checking. It is possible that inserting tX into oStream could fail. An appropriate response would be to throw an exception if the conversation fails.

Converting strings to numbers

Similar to the solution above:

Here’s some sample code to test it:

And the output:

3.4

Note that the second conversation failed and returned false.

17.3 -- std::string length and capacity
Index
17.1 -- std::string and std::wstring

4 comments to 17.2 — std::string construction and destruction

  • DOBRESCU Mihai

    Hi,

    The last two sample programs contain some minor errors.

    Here's the source code for the first one:


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

    using namespace std;

    template <typename T>
    inline string ToString(T tX)
    {
    ostringstream oStream;
    oStream << tX;
    return oStream.str();
    }

    int main()
    {
    string sFour(ToString(4));
    string sSixPointSeven(ToString(6.7));
    string sA(ToString('A'));
    cout << sFour << endl;
    cout << sSixPointSeven << endl;
    cout << sA << endl;
    }

    And its output:


    4
    6.7
    A

    Here's the source code for the second sample program:


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

    using namespace std;

    template <typename T>
    inline bool FromString(const string& sString, T &tX)
    {
    istringstream iStream(sString);
    return (iStream >> tX) ? true : false;
    }

    int main()
    {
    double dX;
    if (FromString("3.4", dX))
    cout << dX << endl;
    if (FromString("ABC", dX))
    cout << dX << endl;
    }

    And its output:


    3.4

  • dragonfi

    I agree with sumanth, this is a fine tutorial indeed, I basically learned c++ from your tutorial.

    I would also like to note a typo in one of the example codes,
    I believe this should be 4:

    string sFour(ToString(7));
  • sumanth

    This site is the best resource for learning C++ that i have come across in years. The concepts presented are arranged in a clear order without overlapping and the explanation and contents is simply marvellous.
    A huge thanks to Alex for coming up with this site. I really appreciate your efforts. Keep up the good work. Waiting for the updates on chapter-16.

    -sumanth

  • Gabe

    Thanks Alex, lots of new stuff I didn't know about. Especially the NULL part of string::string(const char *szCString, size_type unLength)...I wonder if they just forgot.... :D

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">