How to Convert From String to Char in C++


Handling text is an important aspect of software development. The C++ language has two methods of handling text: C-Style strings and C++ Strings. Converting between the two is often necessary when using functions from older libraries. If you need to convert a C++ String into a C-Style string, one approach is to extract the individual characters from the C++ String and place them one at a time into the C-Style string.

Things You'll Need

  • C++ Compiler, such as GCC
  • C++ Integrated Development Environment, such as Eclipse CDT
  • Create a new C++ source code file.

  • Import the C++ String library by writing the following line at the top of your source code:

    include <string>
  • Create a new C++ String in a source code file by writing a line like this:

    string str ("C++ String");

  • Define a character type to hold the characters in the C++ String:

    char temp;

  • Assign a character to temp by using the [] operators of the C++ String. The number between the square brackets will select the character at that location in the C++ String, with the first character starting in index 0. In the example below, the fifth character of string str ('S') is assigned to temp.

    temp = str[5];

Related Searches


  • Photo Credit Images
Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!