basic_string::size and basic_string::resize
abs
TOC
Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

basic_string::size and basic_string::resize 

Illustrates how to use the basic_string::size and basic_string::resize Standard Template Library (STL) functions in Visual C++.


size_type size( ) const;
   void resize(
      size_type n, 
      E c = E( )
   );

NoteNote

The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

The basic_string::size STL function returns the length of the sequence. The basic_string::resize STL function changes the size to the length specified by the first parameter. If the sequence is made longer, the function appends elements with the value of the second parameter. This value defaults to a null. The output of the sample code shows spaces for the null characters. operator<< reads the size of string and outputs each character in the string one at a time.

// size.cpp
// compile with: /EHsc
// 
// Functions:
//    size()
//    resize() ; Defined in header xstring which is included indirectly.
//////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string TestString = "1111122222333334444455555";
   cout << "[" << TestString << "]" << endl
        << "size: " << TestString.size() << endl
        << endl;

   TestString.resize(5);
   cout << "[" << TestString << "]" << endl
        << "size: " << TestString.size() << endl
        << endl;

   TestString.resize(10);
   cout << "[" << TestString << "]" << endl
        << "size: " << TestString.size() << endl
        << endl;

   TestString.resize(15,'6');
   cout << "[" << TestString << "]" << endl
        << "size: " << TestString.size() << endl;
}

[1111122222333334444455555]
size: 25

[11111]
size: 5

[11111     ]
size: 10

[11111     66666]
size: 15

Header: <string>

Show:
© 2016 Microsoft