Search

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.

std::string

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:

4511
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.

Conclusion

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.

Quiz

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
Index
4.4a -- Explicit type conversion (casting)

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

  • cmb

    II'm currently reading a book on C++, and they discuss the issue with the newline character still being in the input stream as well. However, they approach it differently, wherein the author recommends calling the getline() function with empty parameters (wherever it makes sense to put it, i.e after using std::cin). The logic behind it, being that it "eats" the newline character, thus taking it out of the input stream. To me this method, and using the ignore function achieve the same thing. Is there some benefit I'm not quite seeing, as far as using the ignore function goes, over the one the book mentions?

  • Jorge Guimarães

    Trivia:
    On Visual Studio 2019 / Windows 10,

    outputs 2^63 (a really really big number)

  • Kol

    For the appending strings, is it supposed to print "45 volts" or "45volts" because I'm getting the latter?

  • Aditi

    Hello ,

    Can you please elaborate on how std::cin works as an object and calls the getline() function ? I always thought of it as a command under the iostream library that is used to extract an input from the user. I cannot understand how it works like a class object and calls a function of the class .

    Thank you !

  • Darshan

    Hi,

    Even after

    is it a good practise to use cin.ignore,
    or is it only used after

    Thank you

  • Arthur

    here is what I wrote , I am unclear in the answer why initialize variables 'age' and 'letters as integers then change age into a double? I understand the rounding and math but don't understand if there is a reason not to initialize them as doubles in the first place?

    I am still a little unclear on the types of numbers and when to use them but like the write a program quizzes so haven't gone back to review yet. I experimented with the variables age and agePerLetter as int or one of either being double while the other was int and only with both as integer the rounding happened , I am wondering if doing it this way is chancing 'undefined behavior' or something?

    • ethano

      Honestly, my program worked with them uninitialized. You can initialize them, but that isn't technically needed. As long as they're doubles, you are most likely fine.

  • J

    Hello!

    Here's what I came up with. Any tip/suggestions?

  • Alireza

    Hello and thanks,
    So what about these kinds of strings ??

  • 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?

    Regards.

    • Hi Paulo!

      * Line 6: @std::string's default constructor is faster than the constructor that accepts a string literal. Use empty curly brackets.
      * Line 24: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 23: Don't pass 32767 to @std::cin.ignore. Pass @std::numeric_limits<std::streamsize>::max().

      > Is there some way to pass line 24 to the printText() function that I created?
      @std::string can be concatenated with +. Numbers can be converted to a string via @std::to_string.

      • Paulo Filipe

        Helpful helpful helpful!

        Thank you!

        BTW, I am reading a book called c++ primer 5th edition alongside learcpp lessons. Do you guys think it's something that I should be doing? The pace of the book is different than learcpp lessons, and at the very beginning of the book we are presented with while and for loops. Your lessons are very detailed.

        And do you guys know why people at r/learnprogramming say that learncpp is a bad place to learn c++? I am finding these lessons very good!

        • I don't know that book. If you feel like it helps you, keep reading it.

          > learnprogramming
          I've commented on this question here https://www.learncpp.com/cpp-tutorial/b-3-introduction-to-c17/comment-page-1/#comment-381537

        • Alex

          Loops are where programs start to get interesting, so a lot of authors like to rush into that topic, so the examples can be more fun and the programs less trivial.

          I've though about moving the loops related content up, but that would mean splitting other topics up (e.g. to do loops, you at least need an understanding of bool and int and relational operators -- so I'd have to cover those, do loops, then come back to all the other data types and operators -- that seems more confusing than helpful).

  • 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)
    Etc
    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

    Hey,

    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]