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
Instructions
-
-
1
Create a new C++ source code file.
-
2
Import the C++ String library by writing the following line at the top of your source code:
#include <string>
-
-
3
Create a new C++ String in a source code file by writing a line like this:
string str ("C++ String");
-
4
Define a character type to hold the characters in the C++ String:
char temp;
-
5
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];
-
1
References
- Photo Credit Ablestock.com/AbleStock.com/Getty Images