LearnContact
Lesson 159 min read

Strings

A single character variable can only store one letter. To store words, sentences, or any text, C++ provides strings. In this lesson, you will learn how to use std::string and getline() to handle text efficiently.

Introduction

In the previous lesson, you learned about arrays, which allow multiple values of the same data type to be stored under one variable name.

Array Example
int marks[5] = {80, 75, 90, 65, 88};

Arrays work well for collections of values, but what if you want to store a person's name such as Rahul, a city such as Mumbai, or a complete sentence?

Single Character
char grade = 'A';

A single char variable can store only one character. It cannot directly store an entire word or sentence.

The Solution

To store words, sentences, names, addresses, messages, and other textual data, C++ provides strings.

What is a String?

A string is a sequence of characters stored together and used to represent text.

Examples of Strings
"Rahul"
"Hello"
"C++ Programming"
"Mumbai"
"221 Park Street"

Each string can contain letters, numbers, spaces, symbols, or a combination of different characters.

Simple Definition

A string is a collection of characters used to represent textual data.

Why Do We Need Strings?

Without Strings

  • Names would be difficult to store.
  • Addresses could not be handled conveniently.
  • Messages and sentences would be difficult to process.
  • User input involving text would become complicated.
  • Text-based applications would be difficult to build.

With Strings

  • Store and process textual data efficiently.
  • Handle names, emails, addresses, and messages.
  • Accept text input from users.
  • Display meaningful information.
  • Build interactive and user-friendly applications.

Names

Store student names, customer names, employee names, and usernames.

Addresses

Store cities, locations, postal addresses, and delivery information.

Messages

Store notifications, chat messages, descriptions, and comments.

User Information

Store email addresses, account names, and profile information.

Real-World Analogy

Imagine creating a word using individual letter blocks. Each block contains one character, but when the blocks are arranged together, they form meaningful text.

Letter Block Analogy
[ R ] [ a ] [ h ] [ u ] [ l ]
  │     │     │     │     │
  └─────┴─────┴─────┴─────┘
              │
              ▼
           "Rahul"

A string works in a similar way. Multiple characters are combined and treated as one piece of textual data.

Individual Characters
Characters Combined
Form a Sequence
Create Meaningful Text
Character vs String

A character represents one symbol, while a string represents a sequence of characters.

Ways to Create Strings

C++ provides two common approaches for working with strings.

1. Character Array (C-Style)

  • Uses an array of char values.
  • Inherited from the C programming language.
  • Requires manual handling of many operations.
  • Uses a null character to mark the end.
  • More difficult for beginners to manage safely.

2. std::string (Modern C++)

  • Uses the C++ standard library string class.
  • Automatically manages its own storage.
  • Provides useful built-in operations.
  • Can grow and shrink as needed.
  • Recommended for most modern C++ programs.
C-Style String
char name[] = "Rahul";
Modern C++ String
std::string name = "Rahul";
Recommended Approach

For most modern C++ programs, prefer std::string because it is easier to use and provides useful string operations.

The std::string class is provided by the C++ standard library. To use it, include the string header.

Required Header
#include <string>
Typical Program Headers
#include <iostream>
#include <string>

The iostream header provides input and output features such as std::cin and std::cout, while the string header provides std::string.

Include What You Use

Even if a particular compiler appears to make std::string available indirectly, explicitly include <string> when your program uses std::string.

Declaring & Initializing a String

A string variable can be declared first and assigned a value later, or it can be initialized when it is created.

Declaration
std::string name;

This creates an empty string named name.

Initialization
std::string city = "Mumbai";

This creates the string variable city and immediately stores the text Mumbai.

Assignment After Declaration
std::string city;

city = "Mumbai";
PartMeaning
std::stringThe string data type
cityThe variable name
=Assignment operator
"Mumbai"The text stored in the string
Use Double Quotes

String values are written inside double quotes, while individual character values are written inside single quotes.

Memory Representation

Consider a string containing the text Rahul.

Example String
std::string name = "Rahul";
Character Indexes
Index:     0      1      2      3      4
           │      │      │      │      │
           ▼      ▼      ▼      ▼      ▼
Character: R      a      h      u      l

The characters of a std::string can be accessed using indexes. Just like arrays, string indexing begins at 0.

Accessing Characters
std::cout << name[0];
std::cout << name[1];
std::cout << name[4];
Result
R
a
l
Strings Use Indexes

The first character is at index 0. For the string Rahul, valid character indexes are 0 through 4.

Example 1: Declaring and Displaying

Example 1
#include <iostream>
#include <string>

int main()
{
    std::string name = "Rahul";

    std::cout << name;

    return 0;
}

Explanation

  • #include <iostream> provides output functionality.
  • #include <string> provides the std::string class.
  • std::string name creates a string variable.
  • "Rahul" is stored in the name variable.
  • std::cout displays the complete string.
Output
Rahul

Example 2: Taking String Input

The extraction operator can be used with std::cin to read a single word into a string.

Example 2
#include <iostream>
#include <string>

int main()
{
    std::string city;

    std::cout << "Enter your city: ";
    std::cin >> city;

    std::cout << "City: " << city;

    return 0;
}
Create Empty String
Display Input Message
User Enters Text
std::cin Reads One Word
Store Text in city
Display Stored Value
Sample Input and Output
Enter your city: Mumbai
City: Mumbai
Single-Word Input

Using std::cin >> variable reads one whitespace-separated word. It stops when whitespace is encountered.

Reading Multiple Words

A common beginner problem appears when the user enters text containing spaces.

Using std::cin
std::string city;

std::cin >> city;

Suppose the user enters New Delhi.

User Input
New Delhi
Value Stored
New

The extraction operator stops reading when it encounters whitespace. Therefore, only the first word is stored.

std::cin >> variable

  • Reads one whitespace-separated word.
  • Stops at spaces and other whitespace.
  • Suitable for simple single-word input.
  • Input New Delhi stores only New.

std::getline()

  • Reads an entire line.
  • Includes spaces between words.
  • Suitable for names, addresses, and sentences.
  • Input New Delhi stores the complete text.
The Solution

Use std::getline() whenever the input may contain spaces.

Example 3: Using getline()

Example 3
#include <iostream>
#include <string>

int main()
{
    std::string address;

    std::cout << "Enter your address: ";
    std::getline(std::cin, address);

    std::cout << address;

    return 0;
}

Explanation

  • address is created as an empty std::string.
  • The program asks the user to enter an address.
  • std::getline() reads the complete line.
  • Spaces are included in the stored text.
  • The complete address is displayed.
Sample Input and Output
Enter your address: 221 Park Street
221 Park Street
getline() Syntax

std::getline(std::cin, variable) reads characters from standard input until the end of the current line.

Common String Operations

Strings support many useful operations. At this stage, focus on the most common operations for storing, displaying, and reading text.

OperationExample Code
Declare a Stringstd::string name;
Store Textname = "Rahul";
Display Textstd::cout << name;
Read One Wordstd::cin >> name;
Read Complete Linestd::getline(std::cin, name);
Access Charactername[0]
Join StringsfirstName + lastName
Get Lengthname.length()
Joining Strings
std::string firstName = "Rahul";
std::string lastName = "Sharma";

std::string fullName = firstName + " " + lastName;

std::cout << fullName;
Output
Rahul Sharma
Finding String Length
std::string name = "Rahul";

std::cout << name.length();
Output
5
More Operations Later

C++ strings provide many additional operations for searching, replacing, comparing, inserting, and removing text. These can be explored after mastering the basics.

Program Execution Flow

Program Starts
Include Required Headers
Create String Variable
Store Text or Read User Input
Process the String
Display Text
Program Ends

A typical string program creates a string variable, stores or reads textual data, optionally processes that data, and then displays the result.

Real-World Applications

Strings are used in almost every type of application because most software needs to work with textual information.

Student Management

Student names, addresses, course names, and department names.

Banking

Account holder names, branch names, transaction descriptions, and account types.

E-Commerce

Product names, categories, descriptions, customer names, and delivery addresses.

Hospital Management

Patient names, doctor names, diagnoses, and department information.

Games

Player names, level names, dialogue, missions, and item descriptions.

Communication Apps

Messages, comments, notifications, usernames, and status text.

Text Is Everywhere

Whenever an application works with names, messages, descriptions, addresses, commands, or other textual information, strings are involved.

Common Beginner Mistakes

Using char for a Complete Word

A char stores one character, while std::string stores a sequence of characters.

Using Single Quotes for Strings

Single quotes represent character literals. String literals use double quotes.

Expecting std::cin to Read Spaces

The extraction operator reads one whitespace-separated word, not an entire line.

Forgetting the <string> Header

Programs using std::string should explicitly include the string header.

Mixing std::cin and getline() Carelessly

A leftover newline can cause getline() to read an empty line after formatted input.

Using char Incorrectly
// ❌ Incorrect
char name = 'Rahul';

// ✅ Correct
std::string name = "Rahul";
Using the Wrong Quotes
// ❌ Incorrect
std::string city = 'Mumbai';

// ✅ Correct
std::string city = "Mumbai";
Reading Text with Spaces
// Reads one word
std::cin >> city;

// Reads the complete line
std::getline(std::cin, city);
Mixing std::cin and getline()

After using std::cin >> value, a newline may remain in the input stream. A following getline() can read that leftover newline instead of waiting for new text.

Handling the Leftover Newline
#include <iostream>
#include <limits>
#include <string>

int main()
{
    int age;
    std::string name;

    std::cout << "Enter age: ";
    std::cin >> age;

    std::cin.ignore(
        std::numeric_limits<std::streamsize>::max(),
        '\n'
    );

    std::cout << "Enter full name: ";
    std::getline(std::cin, name);

    return 0;
}

Best Practices

  • Prefer std::string over C-style character arrays for most new C++ programs.
  • Include <string> explicitly when using std::string.
  • Use meaningful variable names such as studentName instead of generic names such as str.
  • Use std::cin for simple single-word input.
  • Use std::getline() when input may contain spaces.
  • Use double quotes for string literals.
  • Use single quotes only for individual character literals.
  • Be careful when mixing formatted input with getline().
  • Validate user input when application requirements demand it.
  • Keep string-processing logic clear and readable.
Clear String Variables
std::string studentName;
std::string emailAddress;
std::string deliveryAddress;
Choose the Right Input Method

Use std::cin when one word is expected and std::getline() when a complete line may be entered.

Frequently Asked Questions

What is a string?

A string is a sequence of characters used to represent textual data.

Which class is used for strings in modern C++?

The std::string class is the standard modern C++ type for working with strings.

Which header is required for std::string?

Include the <string> header.

Why does std::cin stop at spaces?

The extraction operator reads one whitespace-separated value and stops when it encounters whitespace.

Which function reads an entire line?

std::getline() reads an entire line, including spaces between words.

What is the difference between char and std::string?

A char stores one character, while std::string stores a sequence of characters.

Do strings use indexes?

Yes. Individual characters in a std::string can be accessed using zero-based indexes.

Can strings contain spaces?

Yes. A std::string can contain spaces. Use std::getline() when reading a complete line from user input.

Can two strings be joined?

Yes. Strings can be concatenated using operations such as the + operator.

How can I find the length of a string?

Use operations such as length() or size() on the std::string object.

Key Takeaways

  • Strings are used to store textual data.
  • A string is a sequence of characters.
  • std::string is the recommended string type for most modern C++ programs.
  • The <string> header provides std::string.
  • String literals use double quotes.
  • Character literals use single quotes.
  • std::cin reads one whitespace-separated word.
  • std::getline() reads an entire line including spaces.
  • String characters can be accessed using zero-based indexes.
  • Strings can be displayed using std::cout.
  • Strings support useful operations such as concatenation and length checking.
  • Strings are used extensively in real-world software applications.

Summary

Strings are one of the most frequently used types in C++ because they allow programs to store and process textual information.

The std::string class provides a convenient modern approach for working with words, names, addresses, messages, descriptions, and sentences. Strings can be declared, initialized, displayed, read from user input, indexed, joined, and measured.

The extraction operator with std::cin is useful for reading a single word, while std::getline() is required when the input may contain spaces. Understanding this difference is essential when building interactive programs.

By mastering std::string, string input, getline(), indexing, and basic operations, you establish a strong foundation for more advanced text processing and prepare for the next important C++ topic: pointers.

Next Lesson →

Pointers