How to set a string null in C++

Hello readers!  In this tutorial, we are going to learn how to set a string null in C++. Let’s have a look at how we can do this. We can do this using the std::string::clear function.


It helps to clear the whole string and sets its value to null (empty string) and the size of the string becomes 0 characters. string::clear does not require any parameters, does not return any error, and returns a null value.

Let’s look at the code as an example

C++: Set a string to null

#include <iostream>
using namespace std;
void clearstring(string str) //function to clear string
  str.clear(); // sets the string to null

  cout << "how string looks after : "; 
  cout << str;

// Driver code
int main()
  string str("Codespeedy coding platform"); //initialize the string
  cout << "how string looks before : ";
  cout << str << endl;
  return 0;


how string looks before : Codespeedy coding platform
how string looks after :

Explanation to the code

First, we will call the function clear string which will clear all the content that already exist then we will use str clear which doesn’t contain any parameter and do not return any value this will set the string value to null.

I hope you have found this post useful!

Leave a Reply

Your email address will not be published. Required fields are marked *