无论我搜索什么值,程序都会说在文件中找不到它。我无法弄清楚我的代码有什么问题。
int main()
{
int array1[MAX_NUMBER];
int length;
int number;
int location;
input (array1, MAX_NUMBER, length);
cout<<"Please enter a number to search for:"<<endl;
cin>>number;
location=search(array1, length, number);
if (location!=-1)
{
cout<<"The number "<<number<<" was found in the "<<location<<" position."<<endl;
}
else
{
cout<<"The number "<<number<<" was not found in the file."<<endl;
}
return 0;
}
void input(int a[], int size, int& number_used)
{
ifstream infile;
int input;
infile.open("numbers.txt");
if (infile.fail())
{
cout<<"Input file opening failed."<<endl;
exit(1);
}
int i;
for (i=0; i<=size; i++)
{
while (infile>>input)
{
a[i]=input;
cout<<a[i]<<endl;
}
}
number_used=i;
}
int search(const int a[], int number_used, int search_value)
{
int start=1;
int end=number_used;
int key=search_value;
while (start<=end)
{
int mid=((start+end)/2);
if (a[mid]==key)
{
return mid;
}
if (a[mid]>key)
{
end=mid-1;
}
else
{
start=mid+1;
}
}
return -1;
}
我的问题是在主代码中还是在搜索功能中?
输入文件:
1
5
6
7
11
19
21
23
33
54
78
97
例如,输入 19,输出为“文件中未找到数字 19”。