如何检查输入是否是数组内的元素

时间:2015-08-01 12:34:38

标签: c++ arrays function for-loop

在提示用户进行选择并输入3后,系统会要求他们从给定的列表中输入名称。如果他们输入的名称不在列表中,则程序需要输出一个声明,表明输入的名称不在列表中

当输入不在数组内的元素时,程序最终在第105行中断。

我已经尝试了所有我能想到的东西,如果我删除了错误捕获程序,程序也能正常工作。

问题出在int SpecTime函数

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

double FastSkier(double [], string[], int);     //Function for finding fastest skier
double AvgTime(double[], int);                  //Function for finding Average
int SpecTime(double[], string[], int);          //Function for finding the time of the name entered
int SkiAndTime(double[], string[], int);        //Function to list all Skiers and their times

int main()
{
const int Size = 5; //size of arrays
string name[Size] = { "Leela" , "Sarah" , "Anna" , "Keesha" , "Heidi" };    //array for Skier names
double time[Size] = {  2.03   ,  2.40   ,  1.85  ,  1.90    ,  2.50 };  //array for Skier times
int choice;

for (int count = 1;; count++)
{
    cout << "Enter 1 to find the fastest Skier" << endl;
    cout << "Enter 2 for the average time of the Skiers" << endl;
    cout << "Enter 3 to find the time of a specific Skier \n";
    cout << "Enter 4 to display all Skiers and their times \n";
    cout << "Enter any other number to end the program \n";
    cout << "\n";
    cin >> choice;

    if (choice == 1)
        FastSkier(time, name, Size);
    else if (choice == 2)
        AvgTime(time, Size);
    else if (choice == 3)
        SpecTime(time, name, Size);
    else if (choice == 4)
        SkiAndTime(time, name, Size);
    else
        return 0;
}

system ("pause");
return 0;
}



double FastSkier(double time[], string name[], int Size)
{
int Loc;                                    //location of data within array, value determined by for-loop
int count;                                  //Counter
double fastest=time[0];                     //variable to find fastest time for Skier, initialized at first value of time
for (count = 1; count < Size; count++)      //cycles through all values of time comparing each one to find the lowest value
{
    if (time[count] < fastest)          
        Loc = count-1;      //subtract 1 from count to adjust for array index
}
cout << "\n";
cout << "The fastest Skier is " << name[Loc] << " with a time of " << fixed << setprecision(2) << time[Loc] << endl;
cout << "\n";

return 0;
}


double AvgTime(double time[], int Size)
{
int Loc;            //location of data within array, acts as a counter in this function 
double Avg;         //Average
double sum = 0;     //sum of all values within time[]

for (Loc = 0; Loc < Size; Loc++)
    sum += time[Loc];
Avg = sum / Size;

cout << "\n";
cout << "The average time for Skiers is " << fixed << setprecision(2) << Avg << endl;
cout << "\n";
cout << "\n";

return 0;
}


int SpecTime(double time[], string name[], int Size)
{
string Skier;   //Name of Skier entered by user
int Loc=0;
bool List = true;

cout << "Skiers \n";

for (int Loc = 0; Loc < Size; Loc++)        //For-loop used to output and display all names of Skiers
{
    cout << "    " << name[Loc] << endl;
}
cout << "Enter the name of the Skier to view their time \n";
cin >> Skier;

for (int Loc = 0;; Loc++)   //For-loop used to find the desired Skier's time
{
    cout << Loc << " beginning of loop" << endl;
    if (Skier == name[Loc])
    {
        cout << Loc << " in correct" << endl;
        cout << Skier << " has the time " << fixed << setprecision(2) << time[Loc] << endl;
        cout << "\n";
        break;
    }
    if(Loc = Size)
    {
        cout << Loc << " in error" << endl;
        cout << "The name you entered is not a current competitor in this competition \n";
        cout << "\n";
        break;
    }
    cout << Loc << " end of loop" << endl;
}
/*if (Skier != name[Loc])   //error trap for inputted names that are not listed
        {
            cout << "The name you entered is not a current competitor in this competition \n";
            cout << "\n";
            //break;
        }*/
return 0;
}


int SkiAndTime(double time[], string name[], int Size)
{
cout << "Skiers             Times" << endl;
cout << "\n";

for (int All = 0; All< Size; All++)
    cout << name[All] << "             " << fixed << setprecision(2) << time[All] << endl;

cout << "\n";

return 0;
}

2 个答案:

答案 0 :(得分:3)

有一个错误:

 if(Loc = Size)

这应该是:

 if(Loc == Size)

第二个错误是:

 if (Skier == name[Loc])

在循环的最后一次迭代中,Loc超出了数组的范围。由于您首先检查此条件,因此Loc的值已超过最后一个条目。

另外,为什么要编写一个没有在for中定义停止条件的循环?应该简单地说:

for (int Loc = 0; Loc < Size; Loc++) 

或者这个:

bool found = false;
for (int Loc = 0; Loc < Size && !found; Loc++) 

然后整个循环更简单:

bool found = false;
for (int Loc = 0; Loc < Size && !found; Loc++)   //For-loop used to find the desired Skier's time
{
    cout << Loc << " beginning of loop" << endl;

    if (Skier == name[Loc])
    {
        cout << Loc << " in correct" << endl;
        cout << Skier << " has the time " << fixed << setprecision(2) << time[Loc] << endl;
        cout << "\n";
        found = true;
    }
}

if ( !found )
{
    cout << Loc << " in error" << endl;
    cout << "The name you entered is not a current competitor in this competition \n";
    cout << "\n";
}

请注意,循环中不再有break语句。原因是found标志设置为true,循环条件包括检查此标志。

实际上,根本不需要这个循环。 std::find函数负责处理:

#include <algorithm>
//...
string* ptrSkier = std::find(name, name + Size, Skier);
if ( ptrSkier == &name[Size] )
{
   // not found
}
else
{
   // found the name
   // the ptrSkier points to the skier found

   // to get the position of the found name:
   size_t Loc = std::distance(name, ptrSkier);

   // rest of code here using Loc
   //...      
}

答案 1 :(得分:1)

首先:PaulMcKenzie说的话。

第二:您对有效竞争对手的检查不正确。单个条目与给定名称不匹配的事实并不意味着该名称不在列表中的其他位置。

您需要在整个列表中搜索给定的名称,然后才能确定它是否存在。从布尔变量name_found开始,最初设置为false。然后遍历所有名称,如果找到正确的名称,则将其标记为true。只有当你到了循环结束,并发现name_found仍然是假的时候,你才能得出结论:给定的名称不存在。