×

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

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 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.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

How to create a library in C++

Before going on to the creation of a library, let’s understand its meaning. What is a library? In simple words, a library is a collection of numerous functions, methods, classes, header files...

7 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.