Characters and Text in C++, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 7.1 Free with a free account

Characters and Text in C++

C++ Programming · Chapter 7: Text and Applied CollectionsSection 7.1 · lesson 43 of 84video coming soon

← The Magic Square PuzzleNext lesson: Utilities for Text →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

How C++ treats textual data.

  • Declare a char, and write escape sequences
  • Use character arithmetic correctly
  • Explain C-style strings and the null terminator
  • Prefer std::string, and know why both exist

Transcript

Everything said in the video, section by section (1,444 words). Read along, or search it.

Opening Question

Two Ways to Hold Text

Names, addresses, messages, file contents. Text is the most common kind of data a program handles. C++ offers two quite different ways of holding it: one inherited from C, and one built for the job. Knowing what each one is, and why both still exist, saves a great deal of confusion later.

Definition

The char Type and Its Literals

A char holds exactly one character, and occupies one byte. A character literal is written in single quotes. Grade holds the letter A. Symbol holds a hash. And digit holds the character seven, not the number seven. Run it, and ask for sizes: the literal A in single quotes is one byte, and the same letter in double quotes is two. Same letter, different type, different size.

Common Mistake

Four Ways a Letter Appears

It's worth pinning down the four ways a letter can appear in source, because mixing them up gives errors that rarely name the real cause. A in single quotes is a character literal: one character, one byte. A in double quotes is a text literal, two bytes long. A with no quotes is an identifier, the name of a variable. And two letters in single quotes isn't what it looks like. Unquoted, the compiler looks for a variable called A, and complains it was never declared. And a char holds one character, so with two inside single quotes, the compiler warns about a multi-character constant. It's legal, but almost never what you meant.

Special Characters

Escape Sequences Written With Backslash

Some characters can't be typed directly. A newline has no visible form, and a quote mark inside quotes would end the literal. These are written as escape sequences: a backslash followed by a letter or symbol. The pair counts as a single character. Backslash t is a tab. Two backslashes make one backslash, because a lone backslash begins an escape. Backslash and a quote mark give a quote that doesn't end the literal. Backslash n is a newline, one character, with code ten. And backslash zero is the null character, with value zero. Its job comes shortly, and it isn't the digit zero.

Key Idea

Every Character Is Stored as a Number

Memory holds numbers and nothing else, so every character is stored as one. The agreed mapping is a character set, and nearly everything builds on ASCII. Print the letter, and you see A. Cast it to int, and it prints 65. A char is a small numeric type wearing a costume. Lowercase a is 97, the digit zero is 48, capital Z is 90. Each group is an unbroken run.

Worked Examples

Doing Arithmetic on Characters

Because characters are numbers, they can take part in arithmetic, and a handful of expressions come up constantly. A plus one is 66, the code for B. Store it back in a char to print it as a letter. A digit minus the character zero gives the digit's numeric value. Seven minus zero is 55 minus 48, which is 7. That's the standard way to turn text into a number. A letter minus small a gives its position in the alphabet, from zero. And subtracting 32 turns a small letter into its capital, because the blocks are 32 apart. But don't extend the reasoning too far. Z plus one isn't small a: it's an open bracket, and six other characters sit in between. Range tests within one block are safe. Arithmetic across blocks isn't.

Limits of ASCII

Unicode and UTF-8 Beyond ASCII

ASCII defines 128 codes. That's enough for English letters, digits, and common punctuation, and nothing else. No Devanagari, no accented vowels, no Greek, no emoji. Unicode is the modern answer: one scheme assigning a code to every character in every writing system. Its most common encoding, UTF-8, stores those codes in one to four bytes each: one byte for ASCII, more for everything else. So once text leaves the ASCII range, one char is no longer one character, and counting bytes is no longer counting letters. The examples here stay inside ASCII. That's a convenience, not a law.

Overview

Character Arrays Versus std::string

A single character is straightforward. Sequences are where C++ shows its history. It has two representations that look similar in use, and are quite different underneath. The C-style form is an array of char, ended by a marker. Five letters take six bytes, and the length isn't stored anywhere. A std::string is an object that looks after itself. It holds the letters plus its own bookkeeping, so it knows how long it is, and it grows when it needs to. That difference shapes everything that follows.

Definition

C-Style Strings and the Null Terminator

A C-style string is an array of char, with one extra element on the end holding backslash zero: the null terminator. Name, size six, holds Rahul: five letters plus one terminator. Leave the size out, and the compiler works it out. Three, for OK. Run it. The array is six bytes, the length found by scanning is five, and element five, the last one, is zero. Everything about the string comes down to that zero.

Common Mistake

When the Array Is Too Small

Size six is correct. Size five looks like exactly the right size, but there is no room for the terminator. C++ catches this one: the compiler refuses, because the initializer has six characters including the terminator. But build the same array by hand, with no terminator, and nothing refuses. Printing it runs on into whatever memory follows, until a zero happens to turn up. That's undefined behavior, and any result at all is possible. Size twenty is fine: the extra elements are unused, and the terminator still marks the end.

Why It Matters

The Terminator Is the Only Boundary

That marker is the only boundary there is. There's no stored length, so a reader begins at the first character and moves forward until it meets the zero. That's also why the literal A in double quotes occupies two bytes: one character followed by a terminator. And it's why unchecked input is so dangerous. Reading into a char array with cin writes however many characters arrive, even past the end, corrupting whatever lies beyond. That isn't a rare accident. It's one of the most exploited faults in the history of software.

Definition

std::string Manages Its Own Storage

A std::string manages its own storage. It has no fixed size, it keeps track of its own length, and it grows when more is put into it. Include the string header. Name starts from a literal. City starts out empty, which is valid, and assignment works as you'd expect. Printing them gives Rahul lives in Bhopal. The size is 5, and the equals-equals compares the text itself: true, printed as 1.

Input Notes

Reading Words and Whole Lines

Two small notes on getting text in. Reading with cin stops at the first space, so it collects one word. Reading an entire line, spaces included, is done with getline. Typing Rahul Sharma shows the split: the first read takes Rahul. Then std::ws skips the space, and getline takes the rest. They come out separately. Either way, the string sizes itself to whatever arrives, so there's no overflow.

Comparison

Choosing Strings Over Char Arrays

Compare the two directly. A char array's size is fixed when declared. A string grows and shrinks. A char array's length must be found by scanning, and a string keeps its own. Overflow isn't detected in a char array, and can't happen in a string. A char array can't be assigned with equals, because it's an array. A string can. And equals-equals on char arrays compares addresses, not contents. Both hold Rahul, and the compiler warns that the comparison is always false. The program prints zero. On strings, it compares the text. An operation that looks correct, compiles, and returns the wrong answer is far worse than one that fails outright. So use std::string.

Context

Why C-Style Text Still Appears

So why does the older form still turn up? Three reasons, and none is likely to go away. Every text literal is one. Rahul, in double quotes in your source, is a C-style array, and a string is built from it. The C standard library, and many system interfaces built on it, take and return C-style text. And decades of existing code use it throughout. You'll read far more of it than you write. So write std::string in new code, without exception at this stage. Learn to read C-style strings, so that legacy code holds no surprises.

Quick Check

Null Character in the Middle

Quick check. A char array holds H, i, and an exclamation mark. Then the middle character is set to backslash zero. What do printing it, and sizeof, show? It prints just H, and sizeof still says four. The array keeps its size, but printing stops at the first zero, which now sits in the middle.

Key Takeaways

Characters, Strings, and Safe Choices

To summarize. A in single quotes is a char; A in double quotes is text, two bytes long. Characters are numbers, so a digit minus the character zero gives its value. Arithmetic is safe within a block, not across blocks. C-style strings end at a terminator, and nothing stops them overflowing. So write std::string, and learn to read C-style text.

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Characters and Text in C++

What is the difference between 'A' and "A" in C++?
A single-quoted 'A' is a char literal, while a double-quoted "A" is a C-style string literal. The char holds one character and occupies one byte. The string literal occupies two bytes: the letter plus a null terminator. An unquoted A is neither, because it is an identifier, so the compiler looks for a variable named A. Two letters in single quotes, like 'AB', give a multi-character constant warning.
How do I convert a digit character to its numeric value in C++?
Subtract the character '0' from the digit character. For example, '7' - '0' is 55 - 48, which is 7 in ASCII, because the digit codes form one unbroken run. Likewise, 'c' - 'a' gives 2, the letter's position counting from zero. This works within one block of characters, such as digits or lowercase letters. It is unreliable across blocks: 'Z' + 1 is '[', not 'a'.
What is the null terminator in a C-style string, and why does it matter?
The null terminator is the character '\0', with value zero, stored after the last letter of a C-style string. It is the only marker of where the text ends, because no length is stored. The declaration char name[] = "Rahul"; creates six elements: five letters plus the terminator. Printing a char array that lacks one runs on into other memory, which is undefined behavior.
Why should I use std::string instead of a char array if both exist in C++?
Use std::string because it tracks its own length, grows as needed, and cannot overflow when reading input. It also behaves intuitively: assignment with = works, and == compares the text itself. With char arrays, == compares addresses, so it compiles but gives the wrong answer. Both forms exist because string literals are C-style arrays, the C library uses them, and legacy code relies on them.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →