从文件中读取int型数据,通过二分查找判断从标准输入获得的int值是否存在于该文件中。
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int binary_search(int key,int a[],int len)
{
int low = 0;
int high = len-1;
while(low <= high)
{
int mid = (low + high) / 2;
if(a[mid] == key)
return mid;
else if(key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
int freadline(const char *filename,int *array)
{
ifstream infile;
int num = 0;
infile.open(filename);
if(!infile)
{
cerr << "error:open file " << filename << " failed" << endl;
return -1;
}
while(infile >> array[num],!infile.eof())
{
if(infile.bad())
{
cerr << "error:IO stream corrupt " << endl;
return -1;
}
if(infile.fail())
{
cerr << "bad data!try again!" << endl;
infile.clear();//reset the stream
infile.sync();//clear buffer
continue;
}
num++;
}
return num;
}
int main()
{
int ret;
int a[100];
int key;
if(0 < (ret = freadline("F:\\mydoc\\algs4-data\\algs4-data\\tinyW.txt",a)))
{
int arraysize = ret;
sort(a,a + arraysize);
while(cin >> key,!cin.eof())
{
if(cin.bad())
{
cerr << "error:IO stream corrupt " << endl;
}
if(cin.fail())
{
cerr << "bad data!try again!" << endl;
cin.clear();
cin.sync();
continue;
}
if(0 >= (ret = binary_search(key,a,arraysize)))
{
cout << "ret-->" <<ret <<endl;
cout<< "key-->" <<key<<endl;
}
}
}
return 0;
}