Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Convert String to Char in C++

Get a single character out of a C++ string with [], at(), or c_str(). Learn which one checks the index, what at() throws, and why an empty string needs care.

BeginnerString Conversion ProgramsExample 7 of 11
convert-string-to-char.cpp
1#include <iostream>
2#include <string>
3using namespace std;
4
5int main() {
6 string str = "Hello";
7
8 // Method 1: Using index operator
9 char ch1 = str[0];
10
11 // Method 2: Using at() method
12 char ch2 = str.at(0);
13
14 // Method 3: Using c_str()
15 const char* cstr = str.c_str();
16 char ch3 = cstr[0];
17
18 cout << "String: " << str << endl;
19 cout << "Character (method 1): " << ch1 << endl;
20 cout << "Character (method 2): " << ch2 << endl;
21 cout << "Character (method 3): " << ch3 << endl;
22
23 return 0;
24}

Sample Output

Character (method 1): H

str[0].

Character (method 3): H

First char through c_str().

In this one

  • How str[0] reads the first character
  • How str.at(0) checks the index and throws out_of_range
  • What c_str() returns and how long the pointer stays valid
  • How to handle an empty string

How it works

  1. 1

    str holds "Hello".

  2. 2

    str[0] gives 'H' with no bounds check.

  3. 3

    str.at(0) gives 'H' and would throw if 0 were invalid.

  4. 4

    c_str() returns a const char* to the same characters; cstr[0] is 'H'.

  5. 5

    Print the results.

Edge cases

Empty string

Set str = "".

str.at(0) throws std::out_of_range. str[0] on an empty string returns the terminating '\0', but any larger index is undefined behavior.

Pointer from c_str after a change

Call str += "!" after getting cstr.

Modifying the string can move its storage, so cstr may now point to freed memory. Call c_str() again after changes.

What's going on

The program extracts a single character from a string. Since a string is a sequence of characters, you can access individual characters by their position (index). The code shows multiple ways to get the first character 'H' from the string "Hello".

Example:

Input string: "Hello"
Output character: 'H' (first character at index 0)

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <string>
Essential for using the string data type and its methods.
Required for all string operations in this program.

Declaring Variables

The program declares:

string str = "Hello";

string is the data type for storing sequences of characters.
str stores the string "Hello", which contains 5 characters: 'H', 'e', 'l', 'l', 'o'.
String indices start at 0, so str[0] = 'H', str[1] = 'e', etc.

Method 1: Using Index Operator []

char ch1 = str[0];

This is the simplest and most common method:

The [] operator accesses a character at a specific index.
str[0] gets the first character (index 0).
Fast and direct access.

How it works:

Strings in C++ are like arrays of characters.
Each character has an index position starting from 0.
str[0] directly accesses the character at position 0.

Advantages:

Simplest syntax
Very fast (direct access)
Familiar to programmers who know arrays

Important Note:

No bounds checking - accessing invalid index (like str[10]) causes undefined behavior.
For safer access, use at() method instead.

Method 2: Using at() Method

char ch2 = str.at(0);

This method provides bounds checking:

at() is a string member function that accesses a character at a specific index.
str.at(0) gets the first character, same as str[0].
Throws an exception if the index is out of bounds.

How it works:

Similar to [] operator but with safety checks.
Verifies that the index is valid before accessing.
Throws std::out_of_range exception for invalid indices.

Advantages:

Safer than [] operator (bounds checking)
Prevents crashes from invalid index access
Better for user input or dynamic strings

Example:

try {

char ch = str.at(0); // Safe

char ch2 = str.at(10); // Throws exception

} catch (const std::out_of_range& e) {

// Handle error

}

Method 3: Using c_str()

const char* cstr = str.c_str();

char ch3 = cstr[0];

This method converts the string to a C-style string:

c_str() returns a pointer to a null-terminated character array.
The result is a const char* (constant character pointer).
You can then access it like a C-style array.

How it works:

1.c_str() converts C++ string to C-style string (char array).
2.The returned pointer points to the first character.
3.Access characters using array notation: cstr[0], cstr[1], etc.

Advantages:

Useful when working with C functions that need char*
Provides direct pointer access
Compatible with legacy C code

Important Notes:

The pointer is const - you cannot modify characters through it.
The pointer becomes invalid if the string is modified.
Use this only when you need C-style string compatibility.

Other Methods (Mentioned but not shown in code)

Method 4: Using front()

char ch4 = str.front();

front() returns a reference to the first character.
More semantic than str[0] - clearly indicates "first character".
Throws exception if string is empty.

Method 5: Using Iterators

char ch5 = *str.begin();

begin() returns an iterator pointing to the first character.
Dereference the iterator (*) to get the character value.
More advanced, used in STL algorithms.

Displaying Results

The program prints:

cout << "String: " << str << endl;

cout << "Character (method 1): " << ch1 << endl;

cout << "Character (method 2): " << ch2 << endl;

cout << "Character (method 3): " << ch3 << endl;

Output:

String: Hello

Character (method 1): H

Character (method 2): H

Character (method 3): H

All three methods produce the same character 'H'.

When to Use Each Method

Index Operator []: Best for most cases - simple and fast. Use when you're certain the index is valid.
at() Method: Best when safety is important - use with user input or dynamic strings where index might be invalid.
c_str(): Use only when you need C-style string compatibility or working with C functions.
front(): Use when you specifically need the first character - more semantic than [0].
Iterators: Use in STL algorithms or when iterating through strings.

Accessing Other Characters

You can access any character in the string:

First character: str[0] or str.front()
Last character: str[str.length() - 1] or str.back()
Character at index i: str[i] or str.at(i)

Example:

string s = "Hello";

char first = s[0]; // 'H'

char last = s[4]; // 'o'

char middle = s[2]; // 'l'

Important Safety Considerations

Bounds Checking:

[] operator: No bounds checking - can cause crashes
at() method: Bounds checking - throws exception for invalid index

Best Practice: Use at() when the index might be invalid, use [] when you're certain it's valid.

Empty Strings:

Accessing any character in an empty string is invalid.
Always check if string is empty: if (!str.empty()) { char ch = str[0]; }

return 0;

This ends the program successfully.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does string("Hi").at(5) do?

Pick an answer to check it.

Question 2

What type does c_str() return?

Pick an answer to check it.

Questions people ask

[] or at()?

Use at() when the index might be wrong and you want an error. Use [] in tight loops where you already know the index is valid.

How do I get the last character?

str.back() or str[str.size() - 1], after checking the string is not empty.

Can I change a character?

Yes: str[0] = 'J'; turns Hello into Jello. You cannot write through c_str().