A Strange Error

Here is the main.cpp from my program .Everything works fine when the while loop is not there...i.e..it is done only once..
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
#include <iostream>
#include <string>
#include "token.h"
#include "rpn.h"
#include "shunt_y.h"
using namespace std;

int main()
{

    deque<token> dt;
    char q;
    string input;
    
    while(1)
    {
    cout<<"Enter the expression:\n>";
    getline(cin,input);
    dt = tokenize(input);
    dt = infix_to_rpn(dt);
    cout<<rpn_eval(dt)<<endl<<"Quit?\n>";
    cin>>q;
    if (q == 'y' )break;
    else continue;
    }
    return 0;

}

At runtime....whenever I opt not to quit....the input string automatically assumes a garbage value...not letting me into type into the prompt...
Looks somewhat like the following:
Enter the expression:
>log ( 10 ^ 5 ) - sin ( 3.142 / 2 )
4
Quit?
>n
Enter the expression:
>0
Quit?
>n
Enter the expression:
>0
Quit?
>

and so on...
The else continue part doesn't really do anything, it would continue without you telling it to. Have you tried putting cin.ignore(numeric_limits<streamsize>::max,'\n'); after cin>>q;?
Last edited on
I did not know about that....Anyway..what do I have to add except that line?
Only putting it shows that numeric_limits is not defined.
You have to include limits. http://www.cplusplus.com/reference/std/limits/

This is because you only read a character, but the user actually inputs at least two of them ('y' and either '\n' or '\n' '\r' for example). The user could also write "yes" there. In any case, you have characters remaining in the stream that you will read with the next getline instead of what you actually wanted. And then you cin another character and the same thing happens again.
Last edited on
Instead of
cin.ignore(numeric_limits<streamsize>::max,'\n');
I tried only cin.ignore();
and it is working..
Any idea why?
Yes, because you probably only have a single character after 'y'. Don't rely on that (as I said, you could accidently type "yes" or"yy" or something like that), include limits and do it as I said.

Look here for what the function does exactly:

http://www.cplusplus.com/reference/iostream/istream/ignore/
Last edited on
But even when I include limits ...the code isn't compiling. Could there be slight differences in how it is used across platforms?
I am using Ubuntu 10.10 and the gcc compilers ..
No, this code is 100% platform independent. What errors do you get? Oh, there is supposed to be a () at the end of max, cause max is a function.
that max was causing problem... It works perfectly when max() is used..
Thank you very much...
Topic archived. No new replies allowed.