我如何检查CIN.FAIL(),但仍使用Ctrl D到达文档的结尾



在Linux终端VI上使用C 。

我的第一类分配是从用户输入中创建一个平均值。我已经完成了这一点,但是为了总的平均值,我们必须使用" ctrl d"才能达到EOF。如果用户进入非数字,我们还必须防止程序崩溃。我遇到的问题是我尝试用来捕获非数字的一切最终也捕获了" Ctrl D"。

这是我当前的代码。我尝试了实现CIN.FAIL((捕获的许多变体。我还尝试了其他捕获非数字的方法,但是我觉得我一定会缺少一些明显的东西,因为这是我的第一个编码班的第一个任务。

#include <iostream>
#include <limits>
using namespace std;
int main()
{
  cout << "Please enter as many test scores as you want then use ctrl+d to 
  calculate the average.";
  double tot {0}, testNum {1};
  while (!cin.eof())
  {
    double input;
    cout << endl << "Enter Score" << testNum << ":";
    cin >> input;
    //need better alt can't use ctrl+d w/ this
    while (cin.fail())
    {
       cin.clear();
       cin.ignore(numeric_limits<streamsize>::max(), 'n');
       cout <<endl << "Invalid entry. nTest scores are graded numerically 
       and don't drop below 0. nPlease type a positive number.";
       cout << " nEnter Score " << testNum << ":";
       cin >> input;
    }
  tot += input;
  testNum++;
  }
double avg = tot / testNum;
cout << endl << "The average score is: " << avg;
return 0;
}

我终于弄清楚了一项工作!我将初始while((更改为(输入> = 0(,并在CIN>>输入后使用此代码。现在,它仍然允许Ctrl D结束代码并捕获其他字符,以免程序崩溃。

      if (!cin.eof())
  {
     while (cin.fail()) //using "ctrl+d" to reach eof doesn't work with this.
     {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        cout << endl << "Invalid entry.";
        cout << "nPlease enter Test Score not Letter Grade.";
        cout << endl << " nEnter Score " << testNum << ":";
        cin >> input;
     }
  }
  else
  {
     break;
  }

您无法测试eof(),直到您尝试阅读某些内容并超过EOF。因此while(eof())几乎总是错误的。

尝试更多这样的东西:

#include <iostream>
#include <limits>
using namespace std;
int main() {
    cout << "Please enter as many test scores as you want then use Ctrl+D to calculate the average.";
    double totalScore = 0;
    int numScores = 0;
    do {
        double score;
        do {
            cout << endl << "Enter Score " << numScores+1 << ":";
            if (cin >> score)
                break;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), 'n');
            cout << endl << "Invalid entry.";
        }
        while (true);
        if (cin.eof())
            break;
        if (score < 0)
        {
            cout << endl << "Test scores are graded numerically and don't drop below 0. nPlease type a positive number.";
            continue;
        }
        totalScore += score;
        ++numScores;
    }
    while (true);
    if (numScores == 0)
        cout << endl << "No scores were entered.";
    else
    {
        double avg = totalScore / numScores;
        cout << endl << "The average score is: " << avg;
    }
    return 0;
}

最新更新