当我输入“x”退出程序时,DataDisplayAndSearch函数由于某种原因导致分段错误。我试过调试,无法弄清问题是什么。这是家庭作业
string DataDisplayAndSearch (int customerCount, string ssn[])
{
//local variables
int index;
int count;
int numberLen;
int numberLocation = NOT_FOUND;
int high;
int low;
int middle;
bool invalidNumber = false;
string choice;
cout << " Social Security Numbers on file are:" << endl;
for (index = 0; index < customerCount; index++)
{
cout << " " << ssn[index] << " ";
}
do
{
cout << endl << endl << " Enter SSN to find (or X to exit):";
invalidNumber = false;
cin >> choice;
if (choice != EXIT && choice != EXIT1)
{
numberLen = choice.length();
if (numberLen < LENGTH || numberLen > LENGTH)
{
invalidNumber = true;
}
for (count = 0; count < LENGTH; count++)
{
if (isprint(choice[count]));
else
{
invalidNumber = true;
}
}
if (choice[IDX2] != DASH || choice[IDX5] != DASH)
{
invalidNumber = true;
}
low = 0;
high = customerCount - 1;
while ((low <= high) && (numberLocation == NOT_FOUND))
{
middle = (low + high) / 2;
if (choice > ssn[middle])
{
high = middle - 1;
}
else if (choice < ssn[middle])
{
low = middle + 1;
}
else
{
numberLocation = middle;
}
}
if (numberLocation == NOT_FOUND)
{
cout << " Error!! Please enter a valid SSN." << endl;
}
if (invalidNumber)
{
cout << " Input dashes and digits " << choice << " are formatted."
<< " SSN must be exactly 11 characters long, formatted as:"
<< " ###-##-###" << endl;
}
} //end of if
} while (((invalidNumber) && (choice != EXIT && choice != EXIT1 ) && (numberLocation == NOT_FOUND)));
}
答案 0 :(得分:0)
当外环出于任何原因退出时,包括choice == EXIT
,函数退出时不提供类型string
的返回值。然后调用者尝试使用不存在的string
对象,因此崩溃。
使用非void
返回类型越过函数的右大括号是未定义的行为。它可能会崩溃,但每次都不会崩溃。如果您可以在命令行上启用其警告功能,例如-Wall
,则编译器可能会警告您这类事情。