stringstream runs into infinite loop

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
42
43
using namespace std;
class token
{
    public:
    bool status;//0 for str & 1 for num
    string str;
    double num;
} ;
typedef vector<token> storage;

int main()
{
    string a;
    token t;
    storage s;
    double x;
    string y;
    getline(cin,a);
    istringstream st;
    st.str(a);
    while(!st.eof())
    {
        if(st>>x,x)
        {
            
            t.status=true;
            t.num=x;
            cout<<t.num<<'\n';

        }
        else
        {
            st>>y;
            t.status=false;
            t.str=y;
            cout<<t.str<<'\n';

        }
        //cout<<t.status;
        s.push_back(t);
    }

}

The number part executes nicely but whenever I put strings into the input....the while starts an infinite loop.
btw_ this is for parsing the input for a calculator program...
Any idea what is going wrong...or a better way to put the different parts of the input line to be analysed separately later?
when >> fails you have to .clear() the stream and every operation will fail until you do that.
then the stream would start right at the beginning again and would never meet the .eof() condition of the loop.Is there a way to take it back through one operation ...which I could use in the beginning of the else block?... seems that the >> is used twice every time a string is encountered.
Are you sure? The http://www.cplusplus.com/reference/iostream/ios/clear/ seems not to mention reseting the get pointer.
By the way, what is st >> x,x supposed to do?
I was wrong about that....recently learnt that it would only clear the last read....in this case ,the error of trying to read a string into a double...
st >>x,x first reads x from the stream and then turns up a true condition if it is double...and a false if it is a string..
and what do you thing st >> x would do?
read x from the input stream until a whitespace is encountered
And what does st >> x return?
When an expression has a , within it, the left part is evaluated but doesn't return anything...the condition of the if block comes from the nature of x.
operator >> returns a reference to istream object which is convertible to a boolean. When an error occurs, This bool = false. Your code gets input and then checks if that input is 0.
Try compiling this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <limits>

int main(){
	double i;
	while(true){
		if(std::cin >> i, i){
			std::cout << "y" << i << "\n";
		}else{
			std::cout << "n" << i << "\n";
			std::cin.clear();
			std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
		}
	}
	return 0;
Input: 0
Output: n0
Input: string
Output: n0
Input: 5
Output y5
Input: string
Output: endless loop of "y5"
Topic archived. No new replies allowed.