4.4b — An introduction to std::string

What is a string?

The very first C++ program you wrote probably looked something like this:

So what is “Hello, world!” exactly? “Hello, world!” is a collection of sequential characters called a string. In C++, we use strings to represent text such as names, addresses, words, and sentences. String literals (such as “Hello, world!”) are placed between double quotes to identify them as a string.

Because strings are commonly used in programs, most modern languages include a built-in string data type. C++ includes one, not as part of the core language, but as part of the standard library.


To use strings in C++, we first need to #include the <string> header to bring in the declarations for std::string. Once that is done, we can define variables of type std::string.

Just like normal variables, you can initialize or assign values to strings as you would expect:

Note that strings can hold numbers as well:

In string form, numbers are treated as text, not numbers, and thus they can not be manipulated as numbers (e.g. you can’t multiply them). C++ will not automatically convert string numbers to integer or floating point values.

String input and output

Strings can be output as expected using std::cout:

This prints:

My name is: Alex

However, using strings with std::cin may yield some surprises! Consider the following example:

Here’s the results from a sample run of this program:

Enter your full name: John Doe
Enter your age: Your name is John and your age is Doe

Hmmm, that isn’t right! What happened? It turns out that when using operator>> to extract a string from cin, operator>> only returns characters up to the first whitespace it encounters. Any other characters are left inside cin, waiting for the next extraction.

So when we used operator>> to extract a string into variable name, only “John” was extracted, leaving “Doe” inside std::cin, waiting for the next extraction. When we then used operator>> to get variable age, it extracted “Doe” instead of waiting for us to input an age. We are never given a chance to enter an age.

Use std::getline() to input text

To read a full line of input into a string, you’re better off using the std::getline() function instead. std::getline() takes two parameters: the first is std::cin, and the second is your string variable.

Here’s the same program as above using std::getline():

Now our program works as expected:

Enter your full name: John Doe
Enter your age: 23
Your name is John Doe and your age is 23

Mixing std::cin and std::getline()

Reading inputs with both std::cin and std::getline may cause some unexpected behavior. Consider the following:

This program first asks you to enter 1 or 2, and waits for you to do so. All good so far. Then it will ask you to enter your name. However, it won’t actually wait for you to enter your name! Instead, it prints the “Hello” line, and then exits. What happened?

It turns out, when you enter a value using cin, cin not only captures the value, it also captures the newline. So when we enter 2, cin actually gets the string “2\n”. It then extracts the 2 to variable choice, leaving the newline stuck in the input stream. Then, when std::getline() goes to read the name, it sees “\n” is already in the stream, and figures we must have entered an empty string! Definitely not what was intended.

A good rule of thumb is that after reading a value with std::cin, remove the newline from the stream. This can be done using the following:

If we insert this line directly after reading variable choice, the extraneous newline will be removed from the stream, and the program will work as expected!

Rule: If reading values with std::cin, it’s a good idea to remove the extraneous newline using std::cin.ignore().

What’s that 32767 magic number in your code?

That tells std::cin.ignore() how many characters to ignore up to. We picked that number because it’s the largest signed value guaranteed to fit in a (2-byte) integer on all platforms.

Technically, the correct way to ignore an unlimited amount of input is as follows:

But this requires remembering (or looking up) that horrendous line of code, as well as remembering what header to include. Most of the time you won’t need to ignore more than a line or two of buffered input, so for practical purposes, 32767 works about as well, and has the benefit of being something you can actually remember in your head.

Throughout these tutorials, we use 32767 for this reason. However, it’s your choice of whether you want to do it the “obscure, complex, and correct” way or the “easy, practical, but not ideal” way.

Appending strings

You can use operator+ to concatenate two strings together, or operator+= to append one string to another.

Here’s an example of both, also showing what happens if you try to use operator+ to add two numeric strings together:

This prints:

45 volts

Note that operator+ concatenated the strings “45” and “11” into “4511”. It did not add them as numbers.

String length

If we want to know how long a string is, we can ask the string for its length. The syntax for doing this is different than you’ve seen before, but is pretty straightforward:

This prints:

Alex has 4 characters

Note that instead of asking for the string length as length(myName), we say myName.length().

The length function isn’t a normal standalone function like we’ve used up to this point -- it’s a special type of function that belongs to std::string called a member function. We’ll cover member functions, including how to write your own, in more detail later.


std::string is complex, leveraging many language features that we haven’t covered yet. It also has a lot of other capabilities that we haven’t touched on here. Fortunately, you don’t need to understand these complexities to use std::string for simple tasks, like basic string input and output. We encourage you to start experimenting with strings now, and we’ll cover additional string capabilities later.


1) Write a program that asks the user to enter their full name and their age. As output, tell the user how many years they’ve lived for each letter in their name (for simplicity, count spaces as a letter).

Sample output:

Enter your full name: John Doe
Enter your age: 46
You've lived 5.75 years for each letter in your name.

Quiz solutions

1) Show Solution

4.5 -- Enumerated types
4.4a -- Explicit type conversion (casting)

355 comments to 4.4b — An introduction to std::string

  • Paulo Filipe

    My solution to the quiz for some helpful review:

    I did it this way to practice previous taught material, and I have a question.
    Is there some way to pass line 24 to the printText() function that I created?


  • Dear Teacher,

    Please let me say you regarding program with line "std::cin.ignore(32767, '\n');" that even with number "1" (std::cin.ignore(1, '\n');) it runs. However with "0" it does not.

    With regards and friendship
    Georges Theodosiou

  • Benur21

    We could also do

    , right?

  • Benur21

    "return 0;" is missing in two code blocks about John Doe

  • Iury

    Here's my code for the quiz, I used static_cast instead of  creating a  variable to store the name's lenght, this way it doesn't count the spaces as name lenght (forgot the simplicity lol).

    • * Line 8: Initialize your variables with brace initializers.

      > this way it doesn't count the spaces as name lenght
      The cast has no effect on the spaces. Your program counts spaces towards the length.

  • Nathan

    Could you compare a string of numbers, such as
    std::string a = 1234
    if (a == 1234)
    If not, how could I do this?

    For context I have two number I want to combine into a string thing so it is easier to check it.
    Insted of if ((x == 56 && y == 24) || ( etc

  • n1fty

  • Diana

    Hello again, it might be a dumb question but in the quiz solution line 11 what does the {0} mean?

  • Diana

    Hi! This code is the same as one piece of code in this tutorial, except I added std::cin.get() so that the console won't close right after the "Hello" sentence is printed, until I hit enter. I have been doing this all the time with Visual Studio 2017 following the previous chapters. But in the code below I need to hit enter twice to get the "Hello" sentence printed. Any idea on why this happens? Thanks.  

    • * Line 10, 16: Initialize your variables with uniform initialization.
      * Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().

      There's one wait in line 17, one in line 18 and another one in line 24. What you described is the expected behavior.

      • Diana

        Thank you for your reply. For the uniform initialization, is

        okay or the below is better? And why do I need to initialize even though the uninitialized code also works?

        • If there is an appropriate 0-value for a type, use that. If there is none, leave the brackets empty. You could initialize strings to "", but doing so would call the std::string::string(const char*) constructor, which is slower than the default constructor while doing the same thing.

          Both @std::cin::operator>> and @std::getline override the variables in every case. Initializing them doesn't make a difference here (Assuming C++11 and later). However, placing your variables in a predictable state and any point in time makes debugging easier and prevents forgetting an initialization when you would have needed it.

  • l1b3rator


    int main()
        std::cout << "Enter your name: ";
        std::string name;
        std::getline(std::cin, name);
        std::cout << "\n";

        std::cout << "What is your age: ";
        double age;
        std::cin >> age;
        std::cout << "\n";

        std::cout << name << " you have lived " << age / name.length() <<" years for each letter in your name"<< std::endl;

        return 0;

    But i've tried to make a function (outside of main) that would return a string and i would like to call that function from main. How do i create a function like that? is it possible?

    • l1b3rator

      Ignore the request, i have found the answer:

      std::string getName()
          std::cout << "Enter your name: ";
          std::string name;
          std::getline(std::cin, name);
          std::cout << "\n";

          return name;

      double getAge()
          std::cout << "What is your age: ";
          double age;
          std::cin >> age;
          std::cout << "\n";

          return age;
      int main()
          std::string name = getName();
          double age = getAge();

          std::cout << name << " you have lived " << age / name.length() <<" years for each letter in your name"<< std::endl;

          return 0;

  • Erk_Forever

    Why not just make age a float or double out of the gate and divide age by name.length? It cuts two variables. Am I missing something here? Is code::Blocks filling in the gaps here on something?

    • Hi!

      * Line 7: @std::string's default constructor is faster
      * Line 11: Use float literals for floats (0.0f instead of 0)
      * Line 14: Limit your lines to 80 characters in length for better readability on small displays.

      One typically uses whole numbers to describe age, I guess that's what made Alex use an int. There's nothing wrong with using a floating point type.

  • Gacrux

    Why if #include <string> is removed, your example below still compiles fine?

    Is #include <string> really necessary?

    I'm using Code::Blocks 17.12 with all the settings described in the first chapters.

    • <iostream> includes <string>. If your remove line 1, 7, 11 your code won't compile. Don't rely on transitive includes, they can cause your code to break in files you're not even working on. If you need something, explicitly include it's header.

      @main is missing a return statement.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]