【问题标题】:Overloading >> operator, fill vector in while loop重载>>运算符,在while循环中填充向量
【发布时间】:2016-08-09 20:36:10
【问题描述】:

我想编写一个包含一些向量的程序witch 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;
};

我不知道我做错了什么,这个函数不会在while循环中完成。 这是我的课

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);
};

感谢您的建议。

【问题讨论】:

    标签: c++ vector overloading


    【解决方案1】:

    如果您只想从同一行读取所有内容,您应该尝试使用getline 而不是while(in &gt;&gt; val):

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

    然后解析字符串以从中提取所有值。否则,如果您正在执行while(in &gt;&gt; val),您需要以某种方式终止输入。

    【讨论】:

    • 当然,我错过了,我必须终止我的循环,因为它不会再次输入值。有什么方法可以识别流中的 Enter 键吗?这可能是我的循环中断。
    • 我认为如果您想在新线路上停下来,那么getline 是您的最佳选择。然后,您可以使用 stringstream 来解析字符串。看看这个:stackoverflow.com/questions/9673708/…
    • 是的,这可能是解决方案。无论如何,非常感谢你,现在我知道是什么问题了。谢谢!
    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多