The C++ basic_string class constructor program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Constructs a string that is empty or initialized by specific characters, or that is a copy of all or part of some other string object or C-string in C++ programming
To show: How to use the C++ basic_string class constructor to construct a string that is empty or initialized by specific characters, or that is a copy of all or part of some other string object or C-string in C++ programming
// the C++ basic_string class constructor example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
// the first member function initializing with a C-string
const char *cstr1a = "Hello Out There.";
basic_string <char> str1a (cstr1a , 8);
cout<<"The cstr1a string initialized by C-string is: "<<str1a<<"."<<endl;
// the second member function initializing with a string
string str2a("How Do You Do?");
basic_string <char> str2b (str2a , 7 , 7);
cout<<"The str2a string initialized by part of the string is: "<<str2b<<"."<<endl;
// the third member function initializing a string with a number of characters of a specific value
basic_string <char> str3a(5, '9');
cout<<"The str3a string initialized by five number 9s is: "<<str3a<<endl;
// the fourth member function creates an empty string and string with a specified allocator
string str4b; // empty string
// string with an allocator
basic_string <char> str4c(str4b.get_allocator());
if (str4c.empty())
cout<<"The str4c string is empty."<<endl;
else
cout<<"The str4c string is not empty."<<endl;
// the fifth member function initializes a string from another range of characters
string str5a("Hello World");
basic_string <char> str5b(str5a.begin() + 5 , str5a.end());
cout<<"The str5b string initialized by another range of characters is: "<<str5b<<"."<<endl;
return 0;
}
Output example:
The cstr1a string initialized by C-string is: Hello Ou.
The str2a string initialized by part of the string is: You Do?.
The str3a string initialized by five number 9s is: 99999
The str4c string is empty.
The str5b string initialized by another range of characters is: World.
Press any key to continue . . .