2016-08-27 4 views
0

Я пишу код, который принимает вход пользователя и вычисляет скидку в зависимости от того, сколько единиц покупает пользователь. Вот моя проблема; Я хочу использовать проверку ввода, чтобы убедиться, что введенный номер находится между 0 и 65535 (максимальный диапазон для неподписанного int), но так, как я установил эту программу, если пользователь вводит число за пределами этого диапазона, которое я испытываю переполнение/недополнение и неправильный номер сохраняется в переменной до того, как он даже попадет в предложения if/else. Я новичок в C++, поэтому, пожалуйста, будьте добрыми. Что я могу сделать, чтобы проверить, находится ли этот номер в правильном диапазоне, когда пользователь вводит его. Кроме того, есть ли способ проверить, что пользователь не ввел символ, отличный от числа? Вот мой код:проверка ввода и переполнение ввода в C++

#include<iostream> 
#include<iomanip> 

using namespace std; 

int main() 
{ 
    // display the instructions and inform the user of the discounts available 

    cout << " This software package sells for $99. Discounts are given according to the following list: \n"; 
    cout << "----------------------------------" << endl; 
    cout << " Quantity\t\t Discount" << endl; 
    cout << "----------------------------------" << endl; 
    cout << " 10 - 19\t\t 20%" << endl; 
    cout << " 20 - 49\t\t 30%" << endl; 
    cout << " 50 - 99\t\t 40%" << endl; 
    cout << " 100 or more\t\t 50%" << endl; 
    cout << "----------------------------------" << endl; 
    cout << "\n\n"; 

    const double price = 99.00; 

    unsigned short quantity; // variable to hold the user's quantity. 
           // shouldn't need more than 2 bytes for this (unsigned short) 

    cout << "How many units are sold?: "; 
    cin >> quantity; 

    double discount; // variable to hold the amount discounted 
    double total; // to hold the total sales price 

    cout << fixed << showpoint << setprecision(2); // set the display of numeric values 

    // calculate the discounted prices 

    if (quantity >= 1 && quantity <= 9) { 

     total = quantity * price; // calculate the total without a discount 

     cout << "There is no discount for this order \n"; 
     cout << quantity << " units were sold at $" << price << " a piece for a total of " << total << endl; 
     cout << "\n"; 
    } 
    else if (quantity >= 10 && quantity <= 19) { 

     discount = (quantity * price) * .20; // calculate the discount 
     total = (quantity * price) - discount; // calculate the total 

     cout << "There is a 20% discount \n"; 
     cout << quantity << " units were sold at $" << price << " with a discount of 20% applied to the order. \n"; 
     cout << "The total cost of the sale is $" << total << endl; 
     cout << "\n"; 
    } 
    else if (quantity >= 20 && quantity <= 49) { 

     discount = (quantity * price) * .30; // calculate the discount 
     total = (quantity * price) - discount; // calculate the total 

     cout << "There is a 30% discount \n"; 
     cout << quantity << " units were sold at $" << price << " with a discount of 30% applied to the order. \n"; 
     cout << "The total cost of the sale is $" << total << endl; 
     cout << "\n"; 
    } 
    else if (quantity >= 50 && quantity <= 99) { 

     discount = (quantity * price) * .40; // calculate the discount 
     total = (quantity * price) - discount; // calculate the total 

     cout << "There is a 40% discount \n"; 
     cout << quantity << " units were sold at $" << price << " with a discount of 40% applied to the order. \n"; 
     cout << "The total cost of the sale is $" << total << endl; 
     cout << "\n"; 
    } 
    else if(quantity > 99 && quantity <= 65535) { 

     // the maximum number allowed in a short int is 65535. I is unrealistic that someone would order more 
     // units than that so this else if clause checks to make sure the number of ordered items is below this number 

     discount = (quantity * price) * .50; // calculate the discount 
     total = (quantity * price) - discount; // calculate the total 

     cout << "There is a 50% discount \n"; 
     cout << quantity << " units were sold at $" << price << " with a discount of 50% applied to the order. \n"; 
     cout << "The total cost of the sale is $" << total << endl; 
     cout << "\n"; 
    } 
    else { 

     // the trailing else clause is used to catch any value for quantity that is 0 or below or any quantity 
     // bigger than what a short int can hold. 

     cout << "You entered an invalid quantity.\n"; 
     cout << "Please enter a value greater than 0 or less than 65,535. \n\n"; 
    } 




    system("pause"); 
    return 0; 
} 

Конечный пункт еще только выполняется, когда значение 0 вводится. Вот пример вывода со значением вне диапазона

This software package sells for $99. Discounts are given according to the following list: 
---------------------------------- 
Quantity    Discount 
---------------------------------- 
10 - 19     20% 
20 - 49     30% 
50 - 99     40% 
100 or more    50% 
---------------------------------- 


How many units are sold?: 65600 
There is a 50% discount 
52428 units were sold at $99.00 with a discount of 50% applied to the order. 
The total cost of the sale is $2595186.00 

Press any key to continue . . . 
+0

Я изучал другие языки в школе. До сих пор в этом классе C++ мы только начинаем и еще не изучили петли While, поэтому, пожалуйста, если вы можете помочь мне найти решение без использования цикла while –

+0

'// не должно быть больше 2 байтов для это (unsigned short) 'Не пытайтесь быть таким умным. Просто используйте обычный 'int' для' quantity' (не 'unsigned int'), и ваши проверки будут работать, как ожидалось. –

+0

Вы можете выучить 'while' петли самостоятельно, они довольно просты, и я уверен, что ваш инструктор будет впечатлен. Кроме того, вы должны прочитать [как спросить] (https://stackoverflow.com/help/how-to-ask), пожалуйста, напишите [Минимальный, полный и проверенный пример] (https://stackoverflow.com/help/mcve). – Xiobiq

ответ

0

Так честно говоря, я не думаю, что это плохой вопрос. Он просто справляется с ошибкой, проверяя все, что приходит из cin >> quantity.

Как описано здесь: User Input of Integers - Error Handling, способ справиться с этим состоит в том, чтобы обернуть cin >> quantity с некоторым кодом обработки ошибок, как показано ниже.

if (cin >> quantity) { 
    // read succeeded 
} else if (cin.bad()) { 
    // IO error 
} else if (cin.eof()) { 
    // EOF reached (perhaps combined with a format problem) 
} else { 
    // format problem 
} 

Это не будет заботиться о целочисленного переполнения, однако, таким образом, полное решение было бы сделать quantity в int и использовать

cout << "How many units are sold?: "; 
if (cin >> quantity) { 
    // read succeeded 

    // check for range 
    if (quantity < 0 || quantity > 65535) { 
     cout << "Number needs to be between 0 and 65535" << endl; 
     return -1; 
    } 
} else if (cin.bad()) { 
    // IO error 
    cout << "Couldn't do a read from stdin :(" << endl; 
    return -1; 
} else if (cin.eof()) { 
    // EOF reached (perhaps combined with a format problem) 
    cout << "Stdin gave EOF :(" << endl; 
    return -1; 
} else { 
    // format problem 
    cout << "Encountered incorrect format" << endl; 
    return -1; 
} 
+0

Спасибо, что не ненавидел мой вопрос LOL. Я думал, что это справедливо –

+0

@ HelpMeI'mStupid Да, ваш вопрос не плох, но он может использовать некоторые улучшения. тем не менее я поднял - проголосовал за вас, потому что это ясно, несмотря на несколько ошибок. –

Смежные вопросы