Lesson 47 +10 XP

Introduction to std::string

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

#include <string>
using namespace std;

Declare and assign

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

cout << greeting << endl;   // Hello

Strings print with cout << 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 <string> to use the string type.
  • string word = "hi"; declares a string with a value.
  • Print strings with cout <<.
  • std::string is string once using namespace std; is in place.