tags:

views:

165

answers:

1

The code below has a method that sets the member field 'x' using the getline() function. I noticed that if I use cin before calling that method, my program would hang the next time I reach the line getline(cin, rangeInput).

Since getline() is using cin, is that why it is causing the program to hang if I have previously used cin? What should I do instead if I want to get a line after I have used cin?

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

class MyClass
{
public:
    MyClass()
    {
    }

    void setXandY()
    {
        string rangeInput = "";
        getline(cin, rangeInput);

        stringstream lineStream(rangeInput);

        int i;
        vector<int> bounds;

        while (lineStream >> i)
            bounds.push_back(i);

        x = bounds[0];
        y = bounds[1];
    }

    int getX() const
    {
        return x;
    }

private:
    int x;
    int y;
};

int main()
{
    int someNum;
    cin>>someNum;

    MyClass c;
    c.setXandY();

    cout << c.getX() ;
}
+1  A: 

You need to clear the input stream - try adding the following after your cin:

cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

The accepted answer to this question gives a good explanation of why/when this is required.

William