Как я могу проверить cin.fail (), но все еще использовать ctrl + d для достижения конца документа?

Использование C ++ на терминале Linux vi.

Мое задание первого класса — создать среднее из пользовательского ввода. Что я и сделал, однако, чтобы получить среднее значение, мы должны использовать «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;
}

0

Решение

Я наконец-то разобрался с работой вокруг! Я изменил инициал while () на while (input> = 0) и использовал этот код после cin >> input. Теперь он все еще позволяет 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;
}
0

Другие решения

Вы не можете проверить 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;
}
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector