getline( cin, exp) problems

I'm having problems with the getline function of the string class. This is what I get everytime I test:

An empty stack has been initiated.

Enter a postfix expression (Y or N)?:y
Enter your expression (separated by blanks): Enter a postfix expression (Y or N)
?:



This is part of the code I don't think I need to put all of it:
I use the getline function in line 20.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
void print_menu();

int main()
{
    Stack obj;
    cout<<"An empty stack has been initiated."<<endl<<endl;
    
    char choice;
    string exp;
    
    do
    {
         print_menu();
         cin>>choice;
         choice = toupper(choice);
         
         switch( choice )
         {
         case 'Y': cout<<"Enter your expression (separated by blanks): ";
                   getline( cin, exp);
                   a_function( exp, obj );
                   while( !( obj.empty() ) )
                   obj.pop();
                   break;
         case 'N': cout << "Test program ended." << endl;
                   break;
         default:  cout << choice << " is invalid." << endl;
         }
    }
    while( (choice != 'N') );

system("pause");
return 0;
}


//------------------------------------------------------------------------------
void print_menu()
{
     cout<<"Enter a postfix expression (Y or N)?:";
}


I would appreciate any help.

Thank you for your time!
Last edited on
i dont see any problem .
if you do this way it will read the expression untill it sees the \n charaacter
if you do this
getline(cin,exp,'?');
it will read the expresion untill it reach to '?'

if you can spicify whats the problem it will be better.
Maybe getline is reading the '\n' character when you press 'y'. Since it can only hold one character, the other stay in the buffer.

Try to clear the buffer before using "getline".
stefanmielke is right. Add while (cin.get()!='\n'); after cin>>choice; and it should be ok.
Last edited on
Topic archived. No new replies allowed.