char at in c++

The char at function in C++ is used to access a specific character in a string or an array of characters. It allows you to retrieve the character at a specified position within the string or array.

To use the char at function in C++, you need to follow these steps:

  1. Declare a string or an array of characters: First, you need to declare a string or an array of characters that you want to access. For example:

cpp std::string str = "Hello, world!";

  1. Use the at function: Next, you can use the at function to access a specific character at a given position within the string or array. The at function takes a single argument, which is the index of the character you want to access. The index starts from 0 for the first character. For example:

cpp char c = str.at(7);

In this example, the character at position 7 (which is the character 'w') will be assigned to the variable c.

  1. Handle exceptions: The at function throws an std::out_of_range exception if the specified index is out of bounds. To handle this exception, you can use a try-catch block. For example:

cpp try { char c = str.at(20); } catch (const std::out_of_range& e) { // Handle the exception }

In this example, if the index 20 is out of bounds for the string str, an std::out_of_range exception will be thrown, and you can handle it in the catch block.

That's how you can use the char at function in C++ to access a specific character in a string or an array of characters.