The C++ clear() member function 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: Using the C++ clear() member function to erase all elements of a string in C++ programming

To show: How to erase all elements of a string in C++ programming using the C++ clear() member function

 

 

// the C++ clear() program example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

string str1("Testing the clear()");

basic_string <char>::iterator StrIter;

 

// normal

cout<<"(normal read and print) str1 string is: "<<str1<<endl;

 

// using iterator, iterate character by character

cout<<"(using iterator to read and print) str1 string is: ";

for (StrIter = str1.begin(); StrIter != str1.end(); StrIter++)

cout<<*StrIter;

cout<<endl;

 

// str1.clear();

cout<<"\nErasing part of the string using erase(13)"<<endl;

str1.erase(13);

cout<<"Operation: str1.erase(13)"<<endl;

cout<<"The modified str1 string is: ";

 

// using iterator

for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)

cout<<*StrIter;

cout<<endl;

 

// for an empty string, begin() is equivalent to end()

cout<<"\nOperation: str1.begin()==str1.end()"<<endl;

if(str1.begin() == str1.end())

cout<<"The str1 string is empty."<<endl;

else

cout<<"The str1 string has some data"<<endl;

// erasing all data

cout<<"\nOperation: str1.erase(13)"<<endl;

cout<<"Erasing all the data using erase()"<<endl;

str1.erase();

 

// re-check

cout<<"The modified string str1 is: "<<endl;

cout<<"\nOperation: str1.begin()==str1.end()"<<endl;

if(str1.begin() == str1.end())

cout<<"The str1 string is empty."<<endl;

else

cout<<"The str1 string has some data"<<endl;

return 0;

}

 

Output example:

 

(normal read and print) str1 string is: Testing the clear()

(using iterator to read and print) str1 string is: Testing the clear()

 

Erasing part of the string using erase(13)

Operation: str1.erase(13)

The modified str1 string is: Testing the c

 

Operation: str1.begin()==str1.end()

The str1 string has some data

 

Operation: str1.erase(13)

Erasing all the data using erase()

The modified string str1 is:

 

Operation: str1.begin()==str1.end()

The str1 string is empty.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index