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 used operator>> again to extract a string into variable age, we got “Doe” instead of “23”. If we had done a third extraction, we would have gotten “23”.

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 numeric value using cin, cin not only captures the numeric 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 numeric 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 numeric 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)

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

  • John

    Hi!
    I wrote the following main part from my code:

    But when i try to run it, the compiler gives me the Error: "no match for call .... ", pointing out on the string line.
    Then I changed the name of the string parameter:

    With these names, the code is working perfectly, but the question is why?
    I mean, why we can't put the same name "choice" there, since the string choice is a variable, and the choice() is a function?
    If I'm not wrong, this kind of naming is valid for int and others types.

    • Alex

      I tried "string choice = choice(number);" with both string and int and got the same result in Visual Studio 2017 -- the compiler complained that choice wasn't a pointer to a function, which means that it's interpreting the rightmost choice as the variable choice, not the function choice. Changing string to int didn't make a difference for me.

      The short answer is: you have a naming conflict, and the compiler can't or won't disambiguate. Changing the name of either the variable or the function resolves the ambiguity.

  • MYLESMAN

    cout << "How many students do you want to enter?" << endl;
        int numberOfStudents;
        cin >> numberOfStudents;

        string *names = new string[numberOfStudents];

        for (int x = 0; x < numberOfStudents; ++x)
        {
            cout << "Enter the name of student number " << x + 1 << "." << endl;
            getline(cin, names[x]);
        }

    When I run this code (it compiles fine) it prints:
    Enter the name of student number 1
    Enter the name of student number 2

    I don't get a chance to enter a student name for the first iteration... However, each iteration after that is fine.

    • Alex

      When you enter the number of students and hit enter, the number of students gets extracted to the numberOfStudents variable, but the newline is still queued for extraction. Then when you go to get the first student name, it just extracts the newline.

      You need to add the following line after asking for the numberofStudents:

      This will get rid of the pesky newline.

      See http://www.learncpp.com/cpp-tutorial/4-4b-an-introduction-to-stdstring/ for more information.

  • Finn St. John

    Can you show tell me what lesson I can learn static_cast so that it will output a float instead of an integer?

  • John

    "To use strings in C++, we first need to #include the <string> header to bring in the declarations for std::string."

    I noticed that this is not needed for GCC 6.3.0 (C++11), the code below compiles, links, and runs without including the <string> header.

    main.cpp

    Enter your full name: Peter Griffin
    Enter your age: 42
    Your name is Peter Griffin and your age is 42

    • John

      Just a note, the code compiles & links with

      g++ -Wall -std=c++98 -pedantic-errors main.cpp

      i.e. after the C++98 standard as well...

    • Alex

      Your compiler may be including the string header for you, or iostream may be including it. Regardless, it is proper form to include it yourself, as you should always explicitly include all dependencies.

  • Mr. Doubt

    From what I tested, uninitialized strings don't carry garbage data like other variables.
    Is this correct? If so, any simple explanation why?

    • Alex

      Generally speaking, fundamental types in C++ are not initialized by default. However, non-fundamental types generally _are_ initialized by default if you do not provide an initializer. std::string is a non-fundamental type, so it gets default initialized.

  • Kiril

    Well my code was

    But how to count the letters only, because with .lenght we get the space between the name also counted and if that happen practically our program calculates a wrong value.
    for example, my name: Jack Richards, the length of that name is 12
    but the program counts the space between Jack and Richards and get's length 13.

    so how we get length without the spaces between?

    • Alex

      If you wanted to remove spaces, you'd need to identify how many spaces were in the string, and subtract those from the string length. This is possible to do like this:

  • OT Young

    When I made my program for the quiz I initialized the 'age' variable as a double, and I did not static cast when making the division happen. Is it better practice to initialize my numerical variables as int and static cast them later than to initialize variables simply how you'd use them?

    • Alex

      It's better to use whatever data type best represents your data. If you're storing only integer ages, then you should use an integer (and static_cast to a floating point if you need to do floating point division). If you need to store fractional ages (e.g. 40.5) then you should use a floating point number.

  • James Ray

    Hi Alex,

    "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"

    I think this should say:

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

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

    May you please explain more about how this works: "std::cin.ignore(32767, 'n');? What does it mean: "ignore up to 32767 characters until a n is removed"?

    • Alex

      No, the sample program is correct -- the program does not work as expected.

      std::cin will remember any characters that were input that could not be extracted to a variable, so they can be subsequently extracted. If we want to get rid of those, we can use std::cin.ignore to do so. The 32767 tells the ignore function to ignore up to 32767 characters (more than we're likely to ever need to ignore), and the '\n' tells ignore to stop ignoring characters if it reaches a '\n' character. Since all user input should be '\n' terminated, this essentially clears out everything.

      • James Ray

        Hi Alex,

        OK, I tested the code myself and I see it runs as you say. Confusing, but I think I understand. Ray gets stored in the next cin for age, so it skips reading the input from the user, and goes straight to printing the output.

        OK, that explanation about ignore makes sense, I guessed that was what it meant but it was good to have that clarification.

  • Nguyen Long

    Hi Alex,
    Thank you for all your helpful tutorial!
    However, I want to ask how to put and return std::string in the formula.
    And I know char can be used to store a character, but not characters. Do we have anything to hold characters?
    Thank you!

    • Alex

      > However, I want to ask how to put and return std::string in the formula.

      I'm not sure I understand what you're asking here.

      char is used to store a character. std::string can be used to store a collection of sequential characters.

  • Avijit Pandey

    I accidently deleted my first comment
    Here is the code:

    I don't understand what is wrong with it.
    when I compile it I get these errors

    |11|error: no matching function for call to 'getline(std::istream&, std::string (&)())'|

    |19|error: request for member 'length' in 'name', which is of non-class type 'std::string() {aka std::basic_string<char>()}'|

    i am using codeblocks for this.
    I tried your code in the solution and it worked perfectly but yours and mine seem pretty much the same to me
    so what is wrong with it??

    • Alex

      You've defined variable name incorrectly, and this is confusing this compiler. Instead of:

      Do:

      • Avijit Pandey

        That did it! Thanks a lot!
        but i still don't understand the difference between name() and name.

        • Alex

          name is just an identifier that we can give to a variable or function. name() means execute the function named name.

          So string name() doesn't make any sense, because we're telling the compiler "define a new string variable and give it the identifier of the function call of the function name". What?! Similarly, std::cout << name doesn't make sense if name is actually a function, because what does it mean to print the value of a function's identifier, rather than the value returned by the function call?

  • Roy

    I have a question: when mixing std::cin and std::getline, you have to remove the newline from the stream after using std::cin, by making use of std::cin.ignore. But why not avoid the issue altogether and use std::getline exclusively? Would there be a disadvantage to using only std::getline instead of std::cin?

    • Alex

      You should use the right tool for the job at hand. If you want to read up to the end of a line (including whitespace), use std::getline. If you want to read up until the first whitespace, use std::cin and manually remove any '\n' you don't want via std::cin.ignore().

      • K750i

        Seeing that std::cin causes all sorts of problems surely it is not the 'right' tool to use. On the other hand, getline() seems to be able to avoid the problems of cin, so shouldn't it be used as pointed out by OP? Unless there's disadvantages which I don't know with my limited C++ knowledge.

        • Alex

          Either could be appropriate depending on what you want to do. getline() isn't helpful if you want to break on spaces, for example. And getline() only works with strings, whereas std::cin can read in all types of data.

  • Józef

    Hi. I kind of dont get the cin.ignore() function. I have this code and when I use cin.ignore() right after entering name I have to press Enter again to evaluate to next line. Why is that?

    • Alex

      cin::ignore has two parameters: the first is the number of characters to get from the input, and the second is the special character (called a delimiter) that will cause the function to stop early.

      When you do a getline to a std::string, all of the input you type (ending with a '\n') is extracted to the string. getline() also discards the '\n', which is key to the next step.

      Then you do cin.ignore(999, '\n'). This tells the compiler, "start discarding characters from std::cin until you hit 999 character or a '\n', whichever comes first". If there were characters in std::cin waiting to be extracted, it would process through those first. But because getline() extracted everything, there's no input waiting.

      Because there's no input in std::cin already, std::cin will ask the user for input. It will continue to do this until the user types 999 characters, or until you hit enter.

      So, in short, cin.ignore() makes you hit '\n' again because getline() discarded the '\n' from the previous string.

      If it had not done so, the '\n'would have been left inside std::cin. Then when cin.ignore() ran, it would have extracted '\n' from std::cin and discarded it. Since that matches the second parameter of ignore(), it would have stopped (not asking the user for any input).

      So, in other words, cin.ignore() is useful if you know that some particular input you want to get rid of is inside std::cin, or if you want to ensure the user has to hit enter.

  • In the following snippet it complains about converting from unsigned int to int[uniform initialisation using the length of string function ] but it works fine with direct initialisation and copy initialisation. I was wondering why this happens??

    Error    1    error C2397: conversion from 'unsigned int' to 'int' requires a narrowing conversion    

    I am using VSExpress 2013 and have used uniform initialisation before too.

    • Alex

      The length() function returns an unsigned integer, and you're using that value to initialize a signed integer. As long as the length of your string falls within the range of a signed integer, this will be fine. But if it ever does not, your code will break (as length will end up negative).

      • Thank you for your reply. But i was wondering how a string could have negative length. Could you give an example?

        Also Thank You very much for creating/maintaining this site. It is very helpful to learn a language from home. I have recommended this site to my friends too.

        • Also why is it not a problem with direct initialisation and copy initialisation? how do they defer from uniform initialisation?

          • Alex

            It should be a problem with all three. It's just that uniform initialization is less permissive about what kind of implicit conversions it will do (which is a good thing).

        • Alex

          A string can never have a (valid) negative length. Let's consider a simple example where an integer is only 8 bytes. In this case, an unsigned integer would have range 0 to 255, and a signed integer from -128 to 127. If the length function returned an unsigned integer between the range 128 to 255 (which is a valid string length), then when you converted that number to a signed integer, it falls outside the range of your signed integer. Your signed integer will interpret the unsigned integer as a signed integer, and the result will be negative (due to the way unsigned and signed integers are stored in binary).

      • Jim

        "The length() function returns an unsigned integer" Probably due to the compiler and the OS in use. In my case, the compiler (Xcode, aka Clang?) warns that (int) "len = string.length();" ! Implicit conversion loses integer precision: 'size_type' (aka 'unsigned long') to 'int'
        So, while I haven't looked it up, apparently the 64-bit (Mac) OS uses a larger (long int) number of bytes.

        One can get rid of the warning simply by using double or even float on "age", but that kind of value rarely gets bigger than 100! 😉

        So glad you are still supporting this site!

        • Alex

          The length function actually returns a size_t, which a type that represents some large unsigned integer (usually the largest integer the architecture supports). If you implicitly cast any unsigned to a signed value, the compiler will complain, but unless you're using the upper-half of the unsigned value's range, it's usually okay in practice.

          You definitely shouldn't use a double or float for this, as that introduces possible precision issues.

  • Mike

    Alex please help

    • Alex

      Not sure. It seems weird to me to have the same statement in the while condition and in the subsequent if statement condition. I think that will cause your program to skip characters.

  • Garry E

    Hi Alex
    Is it possible that you slipped pointers in on us quietly without warning? The answer to my question might
    then be that the long long int returned by the sizeof function refers to an array(?) of pointers and that sufficient memory for 32767 bytes would be allocated when the program was compiled triggered by the keyword
    "string". Guessing that the C++ ignore() function in this case corresponds to the C free() function.

    • Alex

      Kind of. 🙂 The address of the dynamic memory allocated by the std::string is held in a pointer. But you don't need to worry about that at all to use a std::string. It's just an internal detail of how std::string works.

      The ignore() function doesn't have anything to do with strings -- it has to do with ignoring one or more characters that have been buffered for input but not extracted yet. The analog in C++ to C's free() function is the delete keyword. We'll also cover this in chapter 6.

  • Garry E

    Hi Alex- To get a better idea of how strings work I wrote the following program:

    #include <iostream>
    #include <string>

    int main()
    {
        std::cout << " Enter a string of letters: ";
        std::string name;
        std:: getline(std::cin, name);
        std::cout << " Your string is: " << name <<"n";
        
        std::cout << " Your string has " << name.length() << " letters. " <<"n";
        std::cout << " Your string occupied " << sizeof(name) << " bytes of storage space. " <<"n";
        
        return 0;    
    }

    I found that no matter how many characters (up to a thousand or so) I entered the sizeof function always returned a size of 8 bytes.I get it that the max string can be 32767 chars long.  All this is well and
    good but I am confused, because if each char occupies 1 byte does the max string occupy 32767 bytes?
    How is the string stored?
    Garry

    • Alex

      It's hard to answer this question at this point, but I'll try. There are two ways to allocate memory -- statically (which is what we've been doing so far), and dynamically (which we'll cover in chapter 6). std::string uses dynamic memory to hold the chars.

      sizeof() has a limitation in that it will only return the size of statically allocated memory. For this reason, a std::string will always return the same size no matter how much dynamic memory it's allocated to hold the chars.

  • Mike

    Alex please help
    code]

    #include "stdafx.h"
    #include <iostream>
    #include <cctype>
    #include <fstream>
    using namespace std;
    const int siz = 2000;
    int main()
    {
        char ch[siz];
        ifstream infile;
        cout << "Enter name of data file :\n";
        cin.getline(ch, siz);
        infile.open(ch);
        if (!infile.is_open())
        {
            cout << "progam terminating \n";
                exit(EXIT_FAILURE);
        }
        char co[siz];
        infile.getline(co, siz);
        int count(0);
        for (int x(0); siz > x; ++x)
        {
            if ( isalnum(co[x]))
            {
                ++count;
            }

            }
        cout << "number of char = " << count;
    // this was supposed to count the number of chars in the text file but it cant open the text file why ??
        
        return 0;
    }
    [/code]

    • Alex

      Not sure. It opened a file fine for me, and then began counting chars before it crashed. It's probably looking for the text file in a different place than you think it is. Try either putting the text file in the same directory as the executable file, or typing in a full pathname to the file rather than a relative path.

  • Mike

    Alex please help.

    • Alex

      It's crashing because you didn't allocate an array of spr, you only allocated one.

      Instead of:

      It should be:

  • Redingard

    [code]
    #include <string>
    #include <iostream>

    int main()
    {
        std::cout << "Enter your full name.";
        std::string name;

        std::cout << "Enter your age.";
        int age;
        

        
        int letters = name.length();
        int finale = static_cast<double>(age) / letters;

            

        std::cout << "Your name is " << name;
        std::cout << "Your age is " << age;
        std::cout << "You've lived " << finale << "years per letter.";
        return 0;
    }
    [code]

    So I tried doing this quiz without looking too much at the answer, just for the format of static_cast and name.length(). Obviously, it didn't go well. What exactly did I do wrong and how can it be improved to do what I intended?  My error list says that age is an uninitialized local variable.

    • Alex

      You're not too far off. The main thing is you forgot to use std::cin to allow the user to input values for name and age. This means name and age have no values (which is what the compiler is complaining about).

      Another error I see is that you're using static_cast to convert age to a double so you can do a double division, but then you're assigning the result back to an integer variable (losing any decimal points you just worked to preserve).

  • shilpa

    #include <string>
    #include <iostream>

    int main()
    {
        std::cout << "Pick 1 or 2: ";
        int choice;
        std::cin >> choice;

        std::cout << "Now enter your name: ";
        std::string name;
        std::getline(std::cin, name);

        std::cout << "Hello, " << name << ", you picked " << choice << '\n';

        return 0;
    }

    i did not understand why will it not ask us to enter the name during compilation!

    • Alex

      Not sure what you mean. Compilation just turns your code into something you can execute. It doesn't actually execute anything. You have to run your program after compiling it for it to actually produce results.

  • reznov

    Note at solution code: even though std::getline() isn't used after, to make the program expandable it's still usually advicable to still add std::cin.ignore(xxbignumberxx, '\n') at the end.

    This way when in let's say 12 years you wanna reuse the snippet in a program that uses std::getline again later, you don't have to deal with suprises.

    For the rest my version of it does the exact same thing so let's move on to 4.4c 🙂

  • Lauren

    Hi Alex, I see that you said std::cin.ignore(32767, 'n'); is meant to ignore up to 32767 characters until a n is removed. What is the significance of the number 32767? How do you know to use that number? Could you use some other number instead? Thanks.

    • Alex

      32767 is the largest 2-byte signed integer. The first parameter to std::cin.ignore() is an object of type std::streamsize, which is an implementation-defined signed integer type. Given that it's implementation defined, we don't know how big it is, but it's reasonable to assume it's at least 2 bytes.

      You could use some other number, but if you pick a number any larger you risk overflowing the integer on some machines.

      It's actually best/technically correct to #include and use std::numeric_limits::max() instead of 32767, but that's such an ridiculously unmemorable constant. 32767 is easier.

  • Abhishek

    Hi Alex ,

    std::cout << "Pick 1 or 2: ";
        int choice;
        std::cin >> choice;

        std::cout << "Now enter your name: ";
    std::string u;
    cin >> u;
        std::cout << "Hello, " << u << ", you picked " << choice << '\n';
    ----------------------------------------------------------------------
    output :
    Pick 1 or 2: 3
    Now enter your name: asdd
    Hello, asdd, you picked 3
    ----------------------------------------------------------------------
    Ques: Why did "cin" not take newline character "/n" after '3' ?

  • Max

    Can I simply use "cin.ignore() after cin >>;  ? I've used it and it seems to clear the input completely. If I am going to use cin.ignore(32767, '\n'), can I substitute the '\n' with endl?

    • Alex

      No, you shouldn't just use cin.ignore() with no parameters. By default it only ignores one character. You can't substitute '\n' with endl.

  • Zoickx

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

    Perhaps surprisingly, when you run this program, it will ask you to pick 1 or 2, but then skip asking for your name! What happened? "

    This simple inaccuracy got me stuck for a few minutes.I just couldn't figure out why would it not Ask for name - there are no conditionals or anything like that. I even had to run it myself to make sure that's not the case. So, I believe, what you actually meant here was "the program skips reading your name" or something like that?

    Just thought this might help improve the article.
    Otherwise, these lessons are great, thank you kindly for the good work!

  • Damien

    Hi Alex,

    Thanks again for these tutorials and your swift replies to some of my questions so far.

    My question here is in regards to the following - "std::getline() takes two parameters: the first is std::cin, and the second is your string variable".

    I would like to understand this better just for my own understanding, but at the moment am struggling. Not sure the best way to phrase this question, but could you please explain exactly what std::getline() does with the two parameters.

    Thanks!

    • Alex

      I don't know how std::getline() is implemented internally. But the end result is that std::cin is used to read characters from the user, which are placed in the string variable passed in as the second parameter. Unlike the extraction operator (>>), which stops extracting at any whitespace character, std::getline() only breaks on newlines, allowing you to enter text with spaces or tabs in it.

  • Kattencrack Kledge

    Little typo: "Why happened?" was supposed to be "What happened?" after the code example of "Mixing std::cin and std::getline()"

  • Vlad

    While reading 7.12, I realized that I had this question since std::array, when you said they're slower than array[] (not std::array) because of the way they're interpreted under the hood. So, the similar question comes: is std::string slower than C-style strings? Even if it's the preferred way? If it is so, should it still be the preferred way only because it's C++ native (did I get this right?) ?

  • Vlad

    Actually, that result is shown after

    straight from the console, but codeblocks shows the same result.

  • Vlad

    Hello Alex

    I tried running your program where you say std::cin yields a surprise (the result was "Your name is John and your age is Doe"), and, after I enter the two names, then enter, the program displays "Enter your age: Your name is bla and bla bla", then exits. It seems to print the asking age line, but it doesn't wait for any input, it jumps straight to the end.

    I thought maybe it's some typo from my part so I copy-pasted your example and I get the same results. I have codeblocks on archlinux x64. Is this some compiler problem? (it shows success, no warnings/errors).

    • Alex

      std::cin breaks on whitespace, so if you enter "John Doe", it will only extract "John" and leave "Doe" in the input stream waiting for a future extraction. If you want to get a full line of text with spaces in it, you can use std::getline() instead.

      • Vlad

        Yes, but then how did you achieve your result? That's what I should have gotten, too, no? Just to clarify, this is the code:

        Your result is this:

        And here's mine (code is copy-pasted):

        I really hope it's a quirk of codeblocks, my confidence feels threatened. 🙂

        • Alex

          No, you are quite correct. I just made a mistake in my output. Thanks for noticing and pointing it out. I've updated the lesson.

          Your confidence may resume. 🙂

Leave a Comment

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