Lesson 47 +10 XP

Introduction to std::string

A string is a sequence of characters: letters, digits, spaces, and symbols. C++ stores text in the type std::string, which you unlock with the header <string>.

The header

Code

cpp
#include <string>
using namespace std;

Declare and assign

Code

cpp
string greeting = "Hello";
string name;
name = "Ada";

You can declare a string with a value in one step, or declare it empty and assign later. Both are strings.

Print it

Code

cpp
cout << greeting << endl;   // Hello

Strings print with cout &lt;&lt; just like numbers do.

The std name

learncpp calls it std::string because it lives in the std namespace. The line using namespace std; lets you drop the prefix and write plain string - that's the style most tutorials use.

TL;DR

  • Include &lt;string&gt; to use the string type.
  • string word = &quot;hi&quot;; declares a string with a value.
  • Print strings with cout &lt;&lt;.
  • std::string is string once using namespace std; is in place.