I've just started learning C++ and wondered what the purpose of cin.ignore() is and..

This is a discussion on I've just started learning C++ and wondered what the purpose of cin.ignore() is and.. within the C++ Programming forums, part of the General Programming Boards category; cin.get() Code: In this basic thing(don't know what you would call it) #include <iostream> using namespace std; int main () ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    1

    I've just started learning C++ and wondered what the purpose of cin.ignore() is and..

    cin.get()

    Code:
    In this basic thing(don't know what you would call it)
    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
        int num;
        cout<<"Insert number:";
        cin>>num;
        cin.ignore();
        cout<<"You choose:"<<num<<"\n";
        cin.get();
    }
    it works with and without the ' cin.ignore();' and 'cin.get()' so what are they for?
    Last edited by Elliotofhull; 07-09-2010 at 09:54 AM. Reason: code tags

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,796
    This particular use of cin.get() is to pause the program by waiting for input. The idea is that the command prompt window might close when the program terminates, so this keeps it open. If you are running the program from the command prompt, then this would be rather unnecessary.

    The problem is that cin>>num; leaves the newline in the input buffer. cin.get() would then read this newline, thus failing to give the desired "pause the program" effect. Therefore, cin.ignore() is used to read and discard this newline.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    The Autodidact Dante Wingates's Avatar
    Join Date
    Apr 2010
    Location
    Valhalla
    Posts
    56
    See for thyself

    Code:
    #include <iostream>
    
    int main(int argc, char **argv)
    {
        std::string thyName;
    
        std::cout << "Input thy name: ";
        std::cin >> thyName;
        std::cout << "Thy name is \"" << thyName << "\"";
        std::cin.ignore();
        std::cin.get();
    }
    now delete "std::cin.ignore()" and try again
    Last edited by Dante Wingates; 07-09-2010 at 10:46 AM.
    2B OR !2B? That is the question!

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21