C++ Declare string with a given size

In this post, we will discuss how to declare string with given size.

Syntax to declare string of given size

string s(N, X);

The above line of code declares a string of size N filled with character X.

For example,

#include<iostream>
#include<vector>
#include<string>
using namespace std;


int main()
{
	int N = 3;
	char X = '$';
	
	string s1(N, X);
	cout<<"String 1: "<<s1<<"\n\n";
	
	N = 5;
	X = '0';
	
	string s2(N, X);
	cout<<"String 2: "<<s2<<"\n\n";
	
}

Output

declare string with size in C++

Leave a Comment

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