重载 >> 运算符,在 while 循环中填充向量
Overloading >> operator, fill vector in while loop
我想编写包含一些向量的程序 Class。我重载了“>>”运算符,我想把值放在一行中,就像这样
1 2 3 4
这是我的功能
istream &operator>>(istream &in, Wielomian &w){
double val;
w.stopien=0;
while(in>>val){
w.tabw.push_back(val);
w.stopien++;
}
return in;
};
我不知道我做错了什么,这个函数不会在循环中完成。
这是我的 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);
};
感谢您的任何建议。
如果你只想阅读同一行的所有内容,你应该尝试使用 getline
而不是 while(in >> val)
:
string inputStr;
std::getline(in, inputStr);
然后解析字符串以从中提取所有值。否则,如果你正在做 while(in >> val)
你需要以某种方式终止输入。
我想编写包含一些向量的程序 Class。我重载了“>>”运算符,我想把值放在一行中,就像这样
1 2 3 4
这是我的功能
istream &operator>>(istream &in, Wielomian &w){
double val;
w.stopien=0;
while(in>>val){
w.tabw.push_back(val);
w.stopien++;
}
return in;
};
我不知道我做错了什么,这个函数不会在循环中完成。 这是我的 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);
};
感谢您的任何建议。
如果你只想阅读同一行的所有内容,你应该尝试使用 getline
而不是 while(in >> val)
:
string inputStr;
std::getline(in, inputStr);
然后解析字符串以从中提取所有值。否则,如果你正在做 while(in >> val)
你需要以某种方式终止输入。