×

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a large number of them, including strings and characters. When dealing with C++, there will be times when you'll want to convert a character array to a string data structure to improve the efficiency and effectiveness of your code. Let's take a closer look at some of the most prevalent ways for converting char array to string externally, as well as their related examples and output, in this post. But before we get started, let's review what string and char are in C++.

What do you mean by Char ?

In C++, a character is a primitive data type that is also referred to as the 'char' data structure. A single character can be kept in a char data structure, which can represent the alphabet, special characters, numerals, escape sequences, and so on. It is a data structure that takes up only one byte of memory, although the character can also be stored as an integer implicitly. It's worth noting that the ASCII encoding standard is employed by the char data structure in C++. Let us explain what ASCII stands for before you start scratching your head over what it is. ASCII stands for American Standard Code for Information Interchange. It specifies a specific method of converting English characters to integers. For example, the ASCII value of letter ‘d’ is ‘100’, but the ASCII value of 'D' is '68'.

Example :

#include<iostream> 
using namespace std;
int main()
{
    // declaring a character
    char c;
    //giving character value as an input
    cin>> c;
    //displaying the value of character entered
    cout<<c;
}

Output :

T
T

Explanation :

In the above example, we declared a char named c. Then asked the user to provide a value for that char c. The value given by the user will then be printed as the output.

What do you mean by Char Array ?

The sequence or collection of characters in an array in the C++ computer language. A terminated character appears at the conclusion of a character array, indicating that it is the array's last character. Like an array of integers or floats, each index in the array includes a single letter or array.

What do you mean by Strings ?

In the Classic C++ Library, there is a class called string. Please remember that in C++, string is a class, not a fundamental data type. Strings are handled and manipulated using the string class. A defined as a collection of characters that ends with a null character in technical language.

Example :

#include<iostream> 
#include <string>
using namespace std;
int main()
{
    // declaring a string st
    string st;
    //Taking input as value for string st
    cin>> st;
    //displaying the value given to string str
    cout<<st;
}

Output :

Computer
Computer

Explanation :

In the above example, we declared a string named st. Then we asked the user to provide a value for that string st. The value given by the user will then be printed as the output.

Converting Char Array to String in C++ :

We'll give some examples of how to convert a character array to a string.

Method 1: To the Char Array, assign String Literal.

We can immediately assign a char array with a list of characters to the string variable to convert it to a string.

Example :

#include <iostream>
using namespace std;
 
int main() {
   string st = {'c', 'o', 'm', 'p', 'u', 't', 'e', 'r'};
   cout << st;
}

Output :

computer

Explanation :

In the above example, we provide an array of chars directly in the program as a string st and this string was printed as a whole.

Method 2: Using the function string.append().

The method of creating an empty new string and attaching the char array to it to convert the char array to a string. The char array now contains characters in the string.

Example :

#include <iostream>
using namespace std;
 	
int main() {
   string st;
   char charAr[] = {‘c', ‘o’, ‘m’, ‘p’, ‘u’, ‘t’, ‘e’, ‘r’};
   st.append(charAr);
   cout << str;
}

Output :

computer

Explanation :

In the above example, we created an empty new string called st and attached a char array called charAr[] to that string to it to convert the char array to a string. Resulting in printing the char array that contains characters in the string.

Method 3: Append each Char Array element to a String.

To assign each char in a string to a char array, use a looping statement.

Example :

#include <iostream>
using namespace std;
int main() {
   string st = "";
   char charAr[] = {'c', 'o', 'm', 'p', 'u', 't', 'e', 'r'};


   for(char chr: charAr) {
      st += chr;
}
   cout << st;
}

Output :

computer

Explanation :

In the above example, we used the C++ for loop. To add each char of the char array charAr[] to the string st for each statement. With the same repetitive process we printed the whole string as one.


Related Topics

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

For Loop Examples in C++

For Loop A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax of for loop In C++, a...

6 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Continue in C++ While loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the...

4 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

C++ Infinite loop

The term "infinite loop" refers to a loop that does not terminate the loop according to the condition. In some cases, an infinite loop may be required in programming, or...

4 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.