Thread: string cin and buffers

  1. #1
    Registered User Kudose's Avatar
    Join Date
    Jun 2006
    Posts
    92

    string cin and buffers

    Hello all ... I am reading Accelerated C++ (Addison Wesley) and in this example:

    What does the following program do if, when it asks you for input, you type two names (for example, Samuel Beckett)? Predict the behavior before running the program, then try it.


    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
        std::cout << "What is your name? ";
        std::string name;
        std::cin >> name;
        std::cout << "Hello, " << name
                  << std::endl << "And what is yours? ";
        std::cin >> name;
        std::cout << "Hello, " << name
                  << "; nice to meet you too!" << std::endl;
        return 0;
    }
    I assumed it would print out Samuel and ask for another name. This is because earlier in the book they said std::endl flushes the buffer (I thought clearing out the space and Beckett).

    Could someone please explain to my why Samuel is placed into name, output and then Beckett is output without another prompt?

    TIA!

  2. #2
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by Kudose View Post
    in the book they said std::endl flushes the buffer
    There is an output buffer and an input buffer
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  3. #3
    Registered User Kudose's Avatar
    Join Date
    Jun 2006
    Posts
    92
    Simple and effective answer.

    Thanks!

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    cin >> only reads up to a space, so you get the first name.
    The next cin >> checks the input buffer where the inputted data is stored and finds that there is more contents to extract, so it extracts the second name.
    The 3rd cin >> would then find the buffer empty and ask for more input.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed