views:

41

answers:

4

Here's the code :

cout << "Please enter the file path: ";
string sPath;
getline(cin, sPath);
cout << "Please enter the password: ";
string sPassword; getline(cin, sPassword);

Problem is, when I run it it displays "Please enter the file path: " then it displays "Please enter the password: " and then waits for the password. It seems to completely skip the first 'getline()'.

Later edit: Yes there are some input operations done before.

int iOption = 0;
while (iOption == 0)
{
    cout << "(E/D): ";
    switch (GetCH())
    {
    case 'E':
        iOption = 1;
        break;
    case 'e':
        iOption = 1;
        break;
    case 'D':
        iOption = 2;
        break;
    case 'd':
        iOption = 3;
        break;
    default:
        break;
    }
}

And the code for GetCH() in case anyone asks.

char GetCH ()
{
    char c;
    cin >> c;
    return c;
};
A: 

You need to clear whatever available in input stream like below

cin.clear();

cin.ignore(std::numeric_limits<std::streamsize>::max()) 
bjskishore123
The second line doesn't seem to work. It gives me 2 errors (I added the semicolumn).
Andrew
A: 

It looks like the rest of the line that was input for GetCH still remains in the buffer at the time that you call getline, i.e. at least a \n and this is what you are reading in the first getline call. The program doesn't block waiting for user input because the getline request can be satisfied by the partial line still queued for reading.

Consider modifying your GetCH function to read whole lines as well.

E.g. something like (totally untested, I'm afraid):

int GetCH()
{
    std::string inputline;

    // Read until error or we receive a non-empty line
    while( std::getline(std::cin, inputline) && inputline.empty() )
    {
    }

    return inputline.empty() ? EOF : inputline[0];
}
Charles Bailey
A: 

How does your GetCH handle multiple chars? Just Wondering, there doesn't seem to be any error handling

Joe Bentley
This doesn't answer the question so would be more suited to a _comment_ on the question rather than being an _answer_ itself.
Charles Bailey
A: 

I have a cin.clear() before the while loop and have modified the GetCH option to get a whole string with 'getline' and only return the first letter.

char GetCH ()
{
    string c;
    getline(cin, c);
    return c[0];
};

It works like a charm now. Thanks to everyone for the help.

Andrew
While it's perfectly fine to answer your own question, if you're essentially duplicating other answers it makes more sense to reward one of the other answers with an 'acceptance' rather that duplicate it in another answer. I'm not 'begging' for acceptance (I have enough acceptances elsewhere!); just observing that you might want some guidance as to how stackoverflow.com works.
Charles Bailey