我有一个函数,它通过istream输入接收多项式的协效值。我正在努力在其中实现这段代码(不能完全理解istream的工作原理),所以我可以保护它免受错误输入的影响。:
while (!std::cin.good())
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "error";
std::cin >> A;
}进入函数本身:
std::istream& operator>>(std::istream& s, Polynom& c)
{
for (int i = 0; i <= c.degree; i++)
s >> c.coefficents[i];
return s;
}不用说,这就是它在main()中实现的方式。
std::cin >> A;Polynom类:
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];
}
};欢迎任何提示或最佳解决方案:)
发布于 2021-05-26 20:03:25
将我的注释扩展为答案,可以创建一个函数,该函数接受流并在其中使用读取验证循环来获取值。
然后,在operator>>重载中,调用此函数来获取每个值。
可能是这样的:
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;
}您可以将其用作:
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;
}https://stackoverflow.com/questions/67704250
复制相似问题