输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)

How to cin again after enter ctrl + x in a while (cin<<x) loop (cin a struct)

本文关键字:cin lt 一个 结构 循环 ctrl 输入 何再次      更新时间:2023-10-16

这是我的代码

stream& operator>>(istream& is, fraction& f) 
{
is >> f.numerator;
cout << "/";
is >> f.denominator;
}

void insertFraction(fraction*& f, int& n, fraction x)
{
int m = n + 1;
fraction* fNew = (fraction*)realloc(f, m * sizeof(fraction));
if (fNew != NULL)
{
fNew[n] = x;
n++;
f = fNew;
}
}

void enterFraction(fraction*& f, int& n)
{
fraction x;
f = NULL;
n = 0;
int i = 1;
cout << "Enter fraction " << i << " : n";
while (cin >> x)
{
insertFraction(f, n, x);
i++;
cout << "Enter fraction " << i << " or enter Ctrl + X to stop: n";
}
}

问题是,调用函数 enterFraction 后,我可以再次使用 cin,因为 Ctrl + X,请帮我在函数 enterFraction 之后再次使用 cin。谢谢!!

我想您是在问如何在出错后cin恢复。为此,您必须致电

cin.clear();

此外,丢弃错误后可能留下的任何挂起输入可能也是一个好主意。对于那个电话

cin.ignore(std::numeric_limits<std::streamsize>::max());

您需要#include <limits>numeric_limits类。