How To Convert Char To String In C++

A char is a basic data type in C++ that may store a single character value. And a string is a class that symbolizes a series of characters.

It’s a typical task in C++ to convert a char to a string, especially when working with input/output functions or string manipulation. The conversion mechanism selected relies on the application’s particular needs.

Why conversion of char to string in c++ is important

In C++, converting a char to a string is crucial for several reasons:

  1. Many string manipulation methods allow for the modification, concatenation, and searching of strings in c++. To use these functions on a char, a string conversion must first be performed on the char.
  2. Work with strings rather than single characters when doing input/output tasks because they are frequently more convenient. In contrast to reading individual letters and concatenating them, it is easier to read a complete line of text as a string from the console.
  3. Several C++ libraries and APIs require strings as input or output data. Working with these libraries and APIs is made simpler by converting a char to a string.
  4. It is often essential to compare two strings to determine whether they are equal or to determine their relative order in c++.

Approaches for converting char to string in c++

There are several approaches to converting a char to a string in C++. Some of the common approaches are:

  1. Using the ‘string’ constructor
  2. Using ‘string push_back’ function
  3. Using ‘stringstream’
  4. Using ‘to_string’ function
  5. Using the ‘string append’ function

Approach 1: Using the ‘string’ constructor

In C++, we can use the ‘string’ constructor to convert a single character to a string. The constructor takes a single character as an argument and returns a string object that contains that character.

Code:

#include <iostream>
#include <string>
#include <sstream>

int main() {
    // Declare a variable of type 'char' and initialize it with the character 'z'
    char c = 'z';

    // Declare a variable of type 'std::stringstream' to hold the character conversion result
    std::stringstream ss;

    // Write the character 'c' into the stringstream 'ss'
    ss << c;

    // Extract the string value from the stringstream 'ss' and store it in a variable of type 'std::string'
    std::string str = ss.str();

    // Print a message to the console that shows the original character and the resulting string
    std::cout << "The character " << c << " has been converted to the string \"" << str << "\"." << std::endl;

    // Return 0 to indicate successful completion of the program
    return 0;
}

Output:

The character z has been converted to the string "z".

Explanation:

  • We declare a character variable ‘c’ and initialize it to the character ‘z’.
  • We create a stringstream object ‘ss’.
  • We insert the character ‘c’ into the stream using the << operator.
  • We extract the resulting string from the stream using the ‘str’ function and assign it to the string variable ‘str’.
  • We print a message to the console that displays the original character ‘c’ and the resulting string ‘str’.
  • The program returns 0 to indicate successful completion.

Approach 2: Using the ‘string push_back’ function

The ‘string::push_back’ function is a member function of the ‘std::string’ class in C++. It appends a single character to the end of the string, expanding the string’s length by one character.

To convert a character to a string using this approach, you simply create an empty string and then call ‘push_back’ on it, passing the character you want to convert as the argument.

Code:

#include <iostream>
#include <string>

int main() {
    // Declare a variable of type 'char' and initialize it with the character 'Q'
    char c = 'Q';

    // Declare a variable of type 'std::string' and leave it uninitialized
    std::string str;

    // Append the character 'c' to the end of the 'str' string using the 'push_back' method
    str.push_back(c);

    // Print a message to the console that shows the original character and the resulting string
    std::cout << "The character '" << c << "' has been converted to the string \"" << str << "\"." << std::endl;

    // Return 0 to indicate successful completion of the program
    return 0;
}

Output:

The character 'Q' has been converted to the string "Q".

Explanation:

  • We declare a character variable ‘c’ and initialize it to the character ‘Q’.
  • We create an empty string variable ‘str’.
  • We call the ‘push_back’ function on ‘str’, passing the character ‘c’ as its argument.
  • We print a message to the console that displays the original character ‘c’ and the resulting string ‘str’.
  • The program returns 0 to indicate successful completion.

Approach 3:Using ‘stringstream’

You can also use the ‘stringstream’ class, a character or character collection is converted to a string in c++. This approach involves creating an instance of the ‘stringstream’ class, adding the character or characters to the stream, then obtaining the finished string.

Code:

#include <iostream> 
#include <string>    // include the string library
#include <sstream>  // include the string stream library

int main() {
 char ch = 'C'; 

 // create a stringstream object named ss
 std::stringstream ss;

 // insert the character ch into the stringstream object ss
 ss << ch;

 // extract the contents of the stringstream object ss and store it in a string variable str
 std::string str = ss.str();

 // output the converted string to the console
 std::cout << "Converted string: " << str << std::endl;

 return 0;  // return 0 to indicate successful completion of the program
}

Output:

Converted string: C

Explanation:

  • ‘#include <string>’ is used to include the necessary header file that provides the ‘string’ class.
  • ‘#include <stream>’ is used to include the necessary header file that provides the ‘std::stringstream’ class.
  • A ‘char’ variable ‘ch’ is declared and initialized with the value ‘C’.
  • A ‘std::stringstream’ object ‘ss’ is created.
  • The ‘<<’ operator of the ‘std::stringstream’ class is used to write the ‘char’ variable ‘ch’ to the stream ‘ss’.
  • The ‘str()’ function is used to get the string representation of the stream ‘ss’ and assign it to the ‘std::string’ variable ‘str’.
  • The value of the ‘string’ object is printed to the console using the ‘std::cout’ statement.
  • The program returns ‘0’ to indicate successful execution.

Approach 4:Using ‘to_string’ function

In C++, you can also use the ‘to_string’ function to convert a single character or an integer value to a string. This function is defined in the <string> header file and can be called with a single argument representing the value to be converted.

Code:

#include <iostream>
#include <string>

using namespace std;

int main() {
    char inputChar;
    string outputString;

    // Prompt the user to enter a single character
    cout << "Enter a single character: ";

    // Read in the character from the user
    cin >> inputChar;

    // Convert the character to a string using the to_string function
    outputString = to_string(inputChar);

    // Print out the result
    cout << "The character \"" << inputChar << "\" has been converted to the string \"" << outputString << "\"." << endl;

    return 0;
}

Output:

Enter a single character: a
The character "a" has been converted to the string "a".

Explanation:

  • ‘char inputChar’: This declares a variable named ‘inputChar’ of type ‘char’.
  • ‘string outputString’: This declares a variable named ‘outputString’ of type ‘string’.
  • ‘cin >> inputChar’: This reads a single character from the user and stores it in the ‘inputChar’ variable.
  • ‘outputString = to_string(inputChar)’: This converts the ‘inputChar’ ‘variable to a string using the ‘to_string’ function and stores the result in the ‘outputString’ variable.
  • ‘cout << “The character \”” << inputChar << “\” has been converted to the string \”” << outputString << “\”.” << endl;’: This prints out a message to the user that shows the original character input, the resulting string output, and some additional text to make the message more informative.

Approach 5:Using the ‘string append’ function

In C++, you can also use the ‘append’ function of the ‘string’ class to convert a single character or a character array to a string.

Code:

#include <iostream>
#include <string>

using namespace std;

int main() {
  char input_char;
  string output_string;

  // Get a single character input from the user
  cout << "Please enter a character: ";
  cin >> input_char;

  // Convert the character to a string using string append
  output_string.append(1, input_char);

  // Print the result
  cout << "The character \"" << input_char << "\" has been converted to the string \"" << output_string << "\"." << endl;

  return 0;
}

Output:

Please enter a character: A
The character "A" has been converted to the string "A".

Explanation:

  • We include the necessary C++ libraries for input/output and string manipulation.
  • We declare two variables: ‘input_char’ of type ‘char’ and ‘output_string’ of type ‘string’.
  • We use the ‘cout’ object to print a prompt to the user to input a character.
  • We use the ‘cin’ object to read the user’s input character into the ‘input_char’ variable.
  • We use the ‘string’ class method ‘append’ to add the input character to the end of the ‘output_string’ variable, effectively converting the character to a string.
  • We use the ‘cout’ object again to print the resulting string, including the original character as well as the converted string.
  • Finally, we return 0 to indicate successful program execution.

Best Approach for converting char to string in c++

One of the best approaches for converting a character to a string in C++ is to use the std::string constructor. This approach has the following advantages:

  1. Simple and easy to use: Using the std::string constructor to convert a character to a string is a simple and straightforward approach.
  2. Works for all characters: This approach can be used to convert any character to a string, whether it is a printable character or a non-printable character.
  3. Efficient: This approach is efficient because it does not require any additional memory allocation or copying.
  4. Handles null characters: The std::string constructor can handle null characters, which can be useful in some situations.
  5. Supports concatenation: The std::string constructor can be used to concatenate multiple characters into a single string.

Sample Problem For Converting char to string in C++

Sample problem 1

Scenario:

Suppose a company wants to send a message to its employees about an upcoming event. The message contains the initial of the event and the date on which it will occur. The initial of the event is stored as a char variable, and the date is stored as a string. The company wants to concatenate the two variables and send the message to its employees.

Sample Problem:

Write a C++ program that takes an event initially as input from the user, and a date string (e.g. “June 23, 2023”) as a constant, and then converts the event initial from char to string using the ‘string’ constructor approach. Finally, concatenate the converted string with the date string using the ‘+’ operator and output the complete message.

Solution:

  • The program takes input from the user in the form of a single character ‘S’ representing the initial of the event.
  • The constant string “April 15, 2023” is stored in the code itself as a variable.
  • The ‘string’ constructor approach is used to convert the event initial from char to string, and the resulting string is stored in a variable ‘event_str’.
  • The ‘+’ operator is used to concatenate the ‘event_str’ and ‘date’ strings.
  • The final message “The event ‘S’ is scheduled for April 15, 2023.” is outputted to the console.

Code:

#include <iostream>
#include <string>

int main()
{
   // Get input from user
   char event_initial;
   std::cout << "Enter the event initial: ";
   std::cin >> event_initial;

   // Define constant date string
   const std::string date = "April 15, 2023";

   // Convert event initial to string using string constructor
   std::string event_str(1, event_initial);

   // Concatenate event string and date string using '+' operator
   std::string message = "The event '" + event_str + "' is scheduled for " + date + ".";

   // Output the final message
   std::cout << message << std::endl;

   return 0;
}

Output:

Enter the event initial: S
The event 'S' is scheduled for April 15, 2023.

Sample problem 2

Suppose you are building a program for a library management system where you have to concatenate a character with a string to generate a unique identification code for each book. The identification code will consist of the first letter of the book name and a unique number.

Solution:

  • In this example, we first declare a character variable ‘ch’ with the value ‘A’, a string variable ‘bookName’ with the value “The Lord of the Rings”, and an integer variable ‘bookId’ with the value 12345.
  • We then concatenate the character ‘ch’ with the integer ‘bookId’ using the ‘to_string()’ function to convert the integer to a string. This is done by using the + operator to concatenate ‘ch’ and ‘to_string(bookId)’.
  • The resulting string is stored in a new string variable ‘idCode’.
  • Finally, we display the generated ID code using the ‘cout’ statement.

Sample Code:

#include <iostream>
#include <string> // include the string library

using namespace std; // use the standard namespace

int main()
{
   char ch = 'A'; // declare a character variable ch and initialize it with the letter 'A'
   string bookName = "The Lord of the Rings";
   int bookId = 12345; // declare an integer variable bookId and initialize it with a book ID

   // Concatenate a character and an integer using the to_string function and the + operator
   string idCode = ch + to_string(bookId);

   // Display the generated ID code using cout and the << operator
   cout << "The ID code for the book \"" << bookName << "\" is: " << idCode << endl;

   return 0; // return 0 to indicate successful completion of the program
}

Output:

The ID code for the book "The Lord of the Rings" is: A12345

Sample problem 3

A company has a list of employee IDs that are stored as characters. The HR department needs to convert the IDs into strings so they can be easily processed and analyzed.

Solution:

  • ‘char empID[10] = “12345678”;’ initializes the char array with the employee ID.
  • ‘stringstream ss;’ creates a new stringstream object.
  • ‘ss << empID;’ extracts the characters from the char array and puts them into the stringstream.
  • ‘string strID = ss.str();’ retrieves the contents of the stringstream as a string and stores it in a variable called ‘strID’.
  • ‘cout << “Employee ID as a string: ” << strID << endl;’ prints the employee ID as a string to the console.
  • ‘return 0;’ ends the program.

Sample Code:

#include <iostream>
#include <sstream> // include the string stream library
using namespace std;

int main()
{
   char empID[10] = "12345678"; // declare a character array empID and initialize it with a string of characters representing an employee ID
   stringstream ss;             // declare a stringstream object ss

   ss << empID; // write the contents of empID to the stringstream object ss

   string strID = ss.str(); // extract the contents of the stringstream object ss as a string and assign it to strID

   // Output the employee ID as a string to the console
   cout << "Employee ID as a string: " << strID << endl;

   return 0; // return 0 to indicate successful completion of the program
}

Output:

Employee ID as a string: 12345678

Sample problem 4

A restaurant wants to print a receipt for a customer’s order, which includes the quantity and name of the items ordered, as well as the total price. The quantity of each item is represented by a character, and the total price is a double. The restaurant wants to convert the quantity character into a string to include it in the receipt.

Solution:

  • The ‘to_string’ function is used to convert a character ‘quantity’ to a string ‘quantity_str’ and the ‘double price’ to a string ‘total_price_str’.
  • The converted strings are then concatenated with other string literals and printed to the console using ‘cout’.
  • The output displays the quantity and name of the item ordered and the total price, which is formatted to show two decimal places.

Sample Code:

#include <iostream> 
#include <string> // include the string library

int main() {
   char quantity = '3'; // declare a character variable quantity and initialize it with the character '3'
   double price = 12.99; 
   std::string item_name = "Hamburger"; // declare a string variable item_name and initialize it with the value "Hamburger"
  
   std::string quantity_str = std::to_string(quantity); // convert the character quantity to a string and store it in quantity_str
   std::string total_price_str = std::to_string(price); // convert the double price to a string and store it in total_price_str
  
   std::cout << "You ordered " << quantity_str << " " << item_name << "(s)" << std::endl; // output a message that includes the quantity and item name
   std::cout << "Total price: $" << total_price_str << std::endl; // output the total price with a dollar sign
  
   return 0; // return 0 to indicate successful completion of the program
}

Output:

You ordered 51 Hamburger(s)
Total price: $12.990000

Sample problem 5

Consider a program that accepts a user’s name as input in the form of a single character, and then converts it to a string to be used in various places in the program.

Solution:

  • First, we create a variable of type char named “c” and initialize it to “A.”
  • Then, we create an object of the ‘stringstream’ class and name it ‘ss’.
  • Next, we insert the value of ‘c’ into ‘ss’ using the ‘<<‘ operator.
  • We then declare a string variable ‘s’ to hold the converted string value of ‘c’.
  • Finally, we extract the value of ‘ss’ into ‘s’ using the ‘>>’ operator and output the value of ‘s’ to the console.
  • The program takes the input character ‘A’ and converts it to a string.
  • The converted string ‘A’ is then output to the console.

Sample Code:

#include <iostream>
#include <sstream>  // include the string stream library

using namespace std; // using the standard namespace

int main() {
   char c = 'A'; 
   stringstream ss; // create a stringstream object named ss
  
   ss << c; // insert the character c into the stringstream object ss
   string s; // declare an empty string s
   ss >> s; // extract the contents of the stringstream object ss and store it in the string s
  
   cout << s << endl; // output the string s followed by a newline character
   return 0; // return 0 to indicate successful completion of the program
}

Output:

A

Conclusion

In conclusion, there are various ways to convert a ‘char’ to a ‘string’ in C++. The best approach depends on the specific use case and personal preference.

For converting a single ‘char’ to a ‘string’, using the ‘string’ constructor or the ‘to_string’ function is a simple and efficient choice. On the other hand, if you need to concatenate multiple ‘char’ to form a longer string, using the ‘+’ operator or the ‘string’ append function would be a better choice.

Choosing the appropriate strategy based on the demands of the particular issue is crucial. In addition, the sample problems provided in this topic can help understand the practical implementation of these approaches.