C++ String Library - reserve


Advertisements


Description

It request a change in capacity.

Declaration

Following is the declaration for std::string::reserve.

void reserve (size_t n = 0);

C++11

void reserve (size_t n = 0);

Parameters

n − Planned length for the string.

Return Value

none

Exceptions

if an exception is thrown, there are no changes in the string.

Example

In below example for std::string::reserve.

#include <iostream>
#include <fstream>
#include <string>

int main () {
   std::string str;

   std::ifstream file ("test.txt",std::ios::in|std::ios::ate);
   if (file) {
      std::ifstream::streampos filesize = file.tellg();
      str.reserve(filesize);

      file.seekg(0);
      while (!file.eof()) {
         str += file.get();
      }
   std::cout << str;
   }
   return 0;
}

string.htm

Advertisements