首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Istream输入检查

Istream输入检查
EN

Stack Overflow用户
提问于 2021-05-26 19:47:53
回答 1查看 59关注 0票数 0

我有一个函数,它通过istream输入接收多项式的协效值。我正在努力在其中实现这段代码(不能完全理解istream的工作原理),所以我可以保护它免受错误输入的影响。:

代码语言:javascript
复制
while (!std::cin.good())
{
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "error";
    std::cin >> A;
}

进入函数本身:

代码语言:javascript
复制
std::istream& operator>>(std::istream& s, Polynom& c)
{
    for (int i = 0; i <= c.degree; i++)
       s >> c.coefficents[i];

    return s;
}

不用说,这就是它在main()中实现的方式。

代码语言:javascript
复制
std::cin >> A;

Polynom类:

代码语言:javascript
复制
class Polynom
{
     private:
     int degree;
     double* coefficents;

public:
   Polynom();
   Polynom(int size);
   Polynom(const Polynom&);
   ~Polynom();

   int get_degree();
   double get_coefficents(int);

   Polynom operator+(const Polynom&);
   Polynom operator-(const Polynom&);
   Polynom operator*(double p);
   void operator=(const Polynom&);

   friend std::ostream& operator<< (std::ostream& s, const Polynom& c);
   friend std::istream& operator>> (std::istream& s, Polynom& c);

   double& operator()(int i)
   {
       return coefficents[i];
   }
};

欢迎任何提示或最佳解决方案:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-26 20:03:25

将我的注释扩展为答案,可以创建一个函数,该函数接受流并在其中使用读取验证循环来获取值。

然后,在operator>>重载中,调用此函数来获取每个值。

可能是这样的:

代码语言:javascript
复制
template<typename T>
bool get_value(std::istream& input, T& value)
{
    while (!(input >> value))
    {
        // If end of file, don't attempt any more validation
        if (input.eof())
        {
            return false;
        }

        // Clear the error
        input.clear();

        // Ignore the rest of the line
        input.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    // When the loop ends, we have successfully read a value from the stream
    // Return true to tell that
    return true;
}

您可以将其用作:

代码语言:javascript
复制
std::istream& operator>>(std::istream& s, Polynom& c)
{
    double value;

    for (int i = 0; i <= c.degree && get_value(s, value); i++)
        c.coefficents[i] = value;

    return s;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67704250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档