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 →
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.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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++?
How do I convert a digit character to its numeric value in C++?
What is the null terminator in a C-style string, and why does it matter?
Why should I use std::string instead of a char array if both exist in C++?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →