In the previous article, we have discussed about C++ Program to Find of Size of Datatypes. Let us learn how to Convert Single Character to String in C++ Program.
Methods to Convert Single Character to String in c++
In this article, we discuss different methods of how we can convert a single character to a string in c++. The methods that we discuss are given below.
Let’s understand each method one by one.
Method 1-Using “=” operator
In this method, we simply assign a character value to a string. Let’s write code for this.
#include <bits/stdc++.h> using namespace std; int main() { char ch='d'; string str; str=ch; cout<<str; return 0; }
Output
d
Method 2-Using “+=” operator
As we know a string is a collection of characters. So if we take an empty string and add the character to it so we can convert that character into the string. Let’s write code for this.
#include <bits/stdc++.h> using namespace std; int main() { char ch='d'; string str=""; str+=ch; cout<<str; return 0; }
Output
d
Method 3-Using append( ) function
This method is just similar to the += operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write the code for this.
#include <bits/stdc++.h> using namespace std; int main() { char ch='d'; string str; str.append(1,ch); cout<<str; return 0; }
Output
d
Method 4-Using assign( ) function
This method is just similar to the = operator discussed above but It gives us another advantage. By using this method we can append as many characters as we want. Let’s write code for this.
#include <bits/stdc++.h> using namespace std; int main() { char ch='d'; string str; str.assign(1,ch); cout<<str; return 0; }
Output
d
So these are the methods to convert a single character to a string in c++.
C++ is a powerful general-purpose programming language. It is mostly used to develop browsers, operating systems, games and so on. Beginners who want to know more inversions of C++ language can learn the Basic C++ Programs for a better and quick understanding of the coding.