Как я могу заставить оператор while, который принимает целочисленный ввод, реагировать определенным образом на нецелочисленный ввод? - PullRequest
0 голосов
/ 04 апреля 2020

Я пытаюсь создать некоторое время l oop в простой тестовой программе. Эта программа предназначена для суммирования всех целых чисел, введенных пользователем, а также для отображения этой суммы и выхода из l oop после того, как пользователь нажмет «a». Если пользователь вводит что-то отличное от целого числа или «a», программа должна ответить «Неверный ввод. Пожалуйста, повторите попытку» и разрешить пользователю ввести другое число.

Моя программа успешно суммирует целые числа , но если введено нецелое число, отличное от «a», l oop заканчивается, не позволяя пользователю ввести другое значение. Блок кода, начинающийся с if (! Cin), похоже, ничего не делает.

Я думаю, что проблема связана с (!cin), а не с test = to_string(number). Есть ли альтернативный метод обнаружения нецелого числа, который позволил бы этой программе успешно?

Вот программа. Спасибо как всегда за вашу помощь!

#include <iostream>
using namespace std;
#include <string>

int main()
{
int sum = 0;
int number;
string test;
cout << "Enter a series of integers; when you are done entering these integers, press a to display the sum of all integers.\n";
while (cin >> number)
{if (!cin)
    {
    test = to_string(number);
    if (test == "a")
        {break;}
    else 
        {cout << "Invalid input. Please try again.\n";
        continue;}
}
else 
{sum += number;}
}

cout << "The total sum is " << sum << ".\n";

}

Ответы [ 3 ]

0 голосов
/ 04 апреля 2020

Вот решение, которое объединяет программу из блога Phillip Siedler's Bumpy Road to Code (https://bumpyroadtocode.com/2017/07/11/sum-of-integer-range/) с использованием Лакшми while (cin).

Это, кажется, позволяет программе прерваться если введено «а», и ввести недопустимое входное сообщение и позволить пользователю повторить попытку, если введено что-то, кроме целого числа или «а».

Я несколько озадачен тем, почему cin.clear(), за которым следует cin >> test, работает. Если вы очистите cin, то как в cin есть что-то, что можно указать в строке cin >> test? Возможно, я не совсем понимаю, что делает cin.clear().

 #include <iostream>
using namespace std;
#include <string>
//Solution borrows significantly from Philipp Siedler's solution for Chapter 5 Exercise 8 of Programming Practice and Principles: https://bumpyroadtocode.com/category/chapter-05-principles-and-practice-using-c/ 


int main()
{
int sum = 0;
int number;
string test;
cout << "Enter a series of integers; when you are done entering these integers, press a to display the sum of all integers.\n";

while (cin)
{
if (cin >> number)
{sum += number;}
else 
 {cin.clear();
    cin >> test;
    if (test == "a")
        {break;}
    else 
        {
        cout << "Invalid input. Please try again.\n";
        continue;}
  }

}

cout << "The total sum is " << sum << ".\n";


}
0 голосов
/ 04 апреля 2020
  • while (cin >> number) означает «l oop, пока вы можете прочитать целое число» . Ваш l oop закончится, как только вы введете что-нибудь еще; 'a', например.

  • if(!cin) бессмысленно, поскольку эта точка не может быть достигнута, пока не будет прочитано правильное целое число.

  • test = to_string( number ) не преобразует целое число в "a".

Решение ( проверить его ):

#include <iostream>
#include <limits>

int main()
{
  using namespace std;

  char c;
  int sum = 0;
  while ( cin >> c ) // read first character in line; if successful, continue with loop's body
  {
    if ( c == 'a' ) // end of input; you can move this in while condition: while ( cin >> c && c != 'a' )
      break;

    int n;
    if (cin.unget() >> n) // putback in the stream the last read character and try to read an integer
    {
      sum += n;
      continue;
    }

    cout << "Invalid input. Please try again.\n";
    cin.clear(); // failed to read an integer: reset the error flags
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); // eat to the end of new-line
  }

  cout << "The total sum is " << sum << ".\n";
}
0 голосов
/ 04 апреля 2020

Смотрите подробности в комментариях:

#include <iostream>
using namespace std;
#include <string>

int main()
{
int sum = 0;
char ch; // Since we can't know whether user inputs an int or char
cout << "Enter a series of integers; when you are done entering these integers, press a to display the sum of all integers.\n";
while (cin) // Loop until user inputs
{
    cin >> ch;

if (isalpha(ch)) // Check if input is type char and handle as needed
{   
    if (ch == 'a')
        {
            break;
        }
    else 
        {
            cout << "Invalid input. Please try again.\n";
            std::cin.clear(); // Delete the current stream
            std::cin.ignore(32767,'\n'); // Revert back to previous input
            continue;
        }
}
else 
{
    sum += (ch - '0') % 48; // Since we are converting the char to int, handle it properly

}
}
cout << "The total sum is " << sum << ".\n";
}
...