C ++为什么我的输入验证会导致程序崩溃?

时间:2016-11-20 22:34:24

标签: c++ validation

我写了一个简单的程序,显示出售的莎莎酱的总罐子,以及销售的最少和最大类型的莎莎酱。该程序工作正常,除非我故意使用错误的用户输入,如字母和负数。对函数inputValidation的调用似乎有效,直到我完成输入为每个salsa类型销售的所有jar。然后它显示大部分结果和崩溃。

// this program allows a business to keep track of sales for five different types of salsa

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

// function prototype
int inputValidation(int);

int main()
{
    const int SIZE = 5;
    string names[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty" };
    int jars[SIZE];
    int totalSold = 0;

    // get the number of jars sold for each salsa
    int tempJars;
    for (int i = 0; i < SIZE; i++)
    {
        cout << "Enter the number of " << names[i] << " salsa jars sold this past month.\n";
        cin >> tempJars;
        // call to input validation function
        jars[i] = inputValidation(tempJars);
        totalSold += jars[i];
    }

    // determine the lowest and highest salsa type sold
    int lowest = jars[0],
        highest = jars[0],
        leastType,
        greatestType;

    for (int i = 0; i < SIZE; i++)
    {
        if (jars[i] < lowest)
        {
            lowest = jars[i];
            leastType = i;
        }

        if (jars[i] > highest)
        {
            highest = jars[i];
            greatestType = i;
        }
    }

    // display results
    for (int i = 0; i < SIZE; i++)
    {
        cout << "You sold " << jars[i] << " jars of " << names[i] << " salsa.\n";
    }
    cout << "You sold a total of " << totalSold << " jars of salsa.\n"
        << names[leastType] << " salsa sold the least amount of jars, which was " << lowest << " jars sold.\n"
        << names[greatestType] << " salsa sold the most amount of jars, which was " << highest << " jars sold.\n";
}

/*
    definition of function inputValidation
    inputValidation accepts an int value as its argument. It determines that the value is a number that is
    greater than 0. If it is not, then the user is prompted to input an acceptable value. the value is
    returned and stored in the corresponding element of the jars array.
*/

int inputValidation(int jars)
{
    do
    {
        while (cin.fail())
        {
            cin.clear(); // clear the error flags
            cin.ignore(INT_MAX, '\n'); // return cin to usable state
            cout << "You may only enter non negative numbers. Please try again.\n";
            cin >> jars;
        }

        if (jars < 0)
        {
            cout << "You may only enter non negative numbers. Please try again.\n";
            cin >> jars;
        }
    } while (jars < 0);

    return jars;
}

1 个答案:

答案 0 :(得分:1)

如果leastType恰好是五个中最小的一个,则names[leastType]永远不会被初始化并包含随机垃圾。然后尝试访问jars[0]表现出未定义的行为。

同样,如果greatestType最大,那么LocationTextExtractionStrategy永远不会被初始化。