Convert String to Char
Convert String to Char in C++ (5 Programs)
BeginnerTopic: String Conversion Programs
C++ Convert String to Char Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
// Method 1: Using index operator
char ch1 = str[0];
// Method 2: Using at() method
char ch2 = str.at(0);
// Method 3: Using c_str()
const char* cstr = str.c_str();
char ch3 = cstr[0];
cout << "String: " << str << endl;
cout << "Character (method 1): " << ch1 << endl;
cout << "Character (method 2): " << ch2 << endl;
cout << "Character (method 3): " << ch3 << endl;
return 0;
}Output
String: Hello Character (method 1): H Character (method 2): H Character (method 3): H
Understanding Convert String to Char
This program demonstrates 5 different methods to convert a string to a character: using index operator [], at() method, c_str(), front(), and using iterators.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.