【问题标题】:How to cin again after enter ctrl + x in a while (cin<<x) loop (cin a struct)在while(cin<<x)循环(cin a struct)中输入ctrl + x后如何再次cin
【发布时间】:2020-09-12 20:18:48
【问题描述】:

这是我的代码

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.clear();不工作

标签: c++ struct istream


【解决方案1】:

我想你是在问如何让cin 在出错后恢复。为此,您必须调用

cin.clear();

此外,丢弃错误后可能遗留的任何待处理输入可能是个好主意。对于那个电话

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

#include &lt;limits&gt; 需要 numeric_limits 类。

【讨论】:

  • cin.clear();对我没有帮助 TT,我认为那是因为我使用 cin 来 cin 一个结构......
  • 可以使用结构体。如果没有更多细节,很难说真正的问题是什么。
猜你喜欢
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
相关资源
最近更新 更多