Library contents

C++ std::string::at

Read the second character in a validated three-character ASCII booking code.

A simple example

std::string::at

  1. Start with "abc"
  2. Do this Read the second character
  3. Result "b"
Walk past a to reach b. These ASCII characters each occupy one byte in UTF-8.

Syntax

C++ syntax
value.at(1)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Read the seat row

A compact printed code assigns meaning to particular positions. Locate the correct character for the requested field and check the indexing convention before sending the value to the display.

From the programconst std::string value = "4B7"
ResultB
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "4B7";
    std::cout << (value.at(1)) << "\n";
    return 0;
}
Output
B

The middle character is the row.

Advertisements

Read the lab wing

A lab badge encodes its wing in one character of the printed code. Select that character using the language's indexing rules before directing a visitor to the room.

From the programconst std::string value = "2C4"
ResultC
lesson.cpp
#include <iostream>
#include <string>

int main() {
    const std::string value = "2C4";
    std::cout << (value.at(1)) << "\n";
    return 0;
}
Output
C

The second position identifies wing C.

Read a parcel sorting code

The depot scans a parcel marked NC-17. Read the first character to identify the routing area.

GivenNC-17
Worked resultN

What to watch for

Check the length first when accepting arbitrary input. Byte, code-point and UTF-16 indexes can differ outside ASCII.

Documentation for std::string::at