1

I want to write program witch Class, that contains some vector. I overloaded ">>" operator and I want to put values typing them in one line, like this

1 2 3 4

This is my function

istream &operator>>(istream &in, Wielomian &w){
    double val;
    w.stopien=0;
    while(in>>val){
        w.tabw.push_back(val);
        w.stopien++;
    }
    return in;
};

I don't know what I'm doing wrong, this function wont finish while loop. This is my class

class Wielomian{

private:
    int stopien;
    vector<double> tabw;
public:
    Wielomian(){
        stopien=0;
    }
    Wielomian(int s, vector<double> t){
        tabw=t;
        stopien=s;
    }
    Wielomian(Wielomian &w){
        this->stopien=w.stopien;
        this->tabw=w.tabw;
    }

    friend istream &operator>>(istream &in, Wielomian &w);
    friend ostream &operator<<(ostream &out, const Wielomian &w);
};

Thank you for any advice.

1 Answers1

1

If you want to just read everything from the same line you should try using getline instead of while(in >> val):

string inputStr;
std::getline(in, inputStr);

and then parse the string to extract all the values from it. Otherwise, if you're doing while(in >> val) you need to terminate the input somehow.

grigor
  • 1,584
  • 1
  • 13
  • 25
  • Of course, I missed it, i have to terminate my loop, because it wont to put values again. Is any way to recognise a Enter key in stream? It could be my loop-breaking if. – Marcin Poliński Aug 09 '16 at 21:01
  • I think if you want to stop at a new line then `getline` is the way to go. You could then use a stringstream to parse the string. Have a look at this one: http://stackoverflow.com/questions/9673708/tell-cin-to-stop-reading-at-newline – grigor Aug 09 '16 at 21:06
  • Yes, This may be the solution. Anyway, thank you very much, now i know what was a problem. Thanks! – Marcin Poliński Aug 09 '16 at 21:20