C Простой Калькулятор Ошибка

Я хочу сделать так, что если в начале введен символ вместо 1, 2, 3 или 4, он зациклится, кроме как

cout << "You have entered a incorrect operator" << endl;

Я пробовал несколько вещей, включая default: случай, но это, кажется, не влияет на это.

Кто-нибудь может пролить свет?

http://pastebin.com/9U7sEEzL

#include <iostream>
#include <string>

void start()
{
using namespace std;

cout << "Welcome to my Basic Mini-Calculator!" << endl;
}

int choice()
{
using namespace std;

int uChoice;

cout << endl << "What do you want to do?" << endl;
cout << "1) Add" << endl;
cout << "2) Subtract" << endl;
cout << "3) Multiply" << endl;
cout << "4) Divide" << endl;
cout << endl << "Waiting for input... (enter a number): ";
cin >> uChoice;
cout << endl;

while( uChoice != 1 && uChoice != 2 && uChoice != 3 && uChoice != 4 );

switch ( uChoice )
{
case 1:
cout << endl << "You chose addition." << endl;
break;

case 2:
cout << endl << "You chose subtraction." << endl;
break;

case 3:
cout << endl << "You chose multiplication." << endl;
break;

case 4:
cout << endl << "You chose division." << endl;
break;
}

return uChoice;}

int input( bool i = false )
{
using namespace std;

string text;

text = ( i == true ) ? "Enter another number: " : "Enter a number: ";
cout << endl << text;

float number;
cin >> number;

return number;
}

int work( int one, int two, int todo )
{
using namespace std;

float answer;

switch ( todo )
{
case 1:
answer = one + two;
break;

case 2:
answer = one - two;
break;

case 3:
answer = one * two;
break;

case 4:
answer = one / two;
break;

default: cout << "Please choose a proper number (1-4)" << endl;
}return answer;
}

void answer( int theanswer )
{
using namespace std;

cout << endl << "The answer is " << theanswer << "." << endl;
cout << endl << "Hit Return to exit.";

cin.clear();
cin.ignore( 255, '\n' );
cin.get();
}

int main()
{
using namespace std;

start();

int todo = choice();

float one = input();
float two = input( true );

float theanswer = work( one, two, todo );answer( theanswer );

return 0;
}

-3

Решение

Просто добавьте do:

do
{
cout << endl << "What do you want to do?" << endl;
cout << "1) Add" << endl;
cout << "2) Subtract" << endl;
cout << "3) Multiply" << endl;
cout << "4) Divide" << endl;
cout << endl << "Waiting for input... (enter a number): ";
cin >> uChoice;
cout << endl;

} while( uChoice != 1 && uChoice != 2 && uChoice != 3 && uChoice != 4 );
2

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

Когда вы пытаетесь прочитать число, но получаете неверный ввод для этого, поток переходит в «состояние сбоя». Вы можете проверить это с помощью cin.fail () или использовать весь поток в качестве аргумента:

// try reading
while(!(cin >> n))
{
cin.clear(); // reset fail state
string s;
getline(cin, s); // discard remaining line
}

Тем не менее, в следующий раз, пожалуйста, уменьшите ваш код до минимального примера.

1

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