Newbie here reporting for duty(help). I'm writing a Binary Search program and I'm stuck in how to get an input from command line to either send it up to the array if it's a number or quit the program if it's an 'x'. So far I've only been taking one type of input only. It's either a int or char, but how do I take an input if it can be either one of them at any giving time. I played around with taking the input as a char and convert it to an int if it's not an x, but because it's a char, cin will only take the very first character. So 34, will only register as 3 and then 4 as if it's two inputs. Plus the conversion doesn't work in my favor either. I'm just stuck here and any help would be greatly appreciated.
thanks
my code is below. My problems start from the "while" statement.
---------------------------------------------
#include <iostream>
#include <string>
using namespace std;
int Binsearch(int data[], int numElements, int searchKey)//this is the function which does the binary search
{
int search;
int total = numElements/2;
for(int i=(numElements/2); i < numElements; i = i)
{
if (searchKey == data[i])
{ search = i;
break;
}
cout << "i = "<< i;
if (searchKey > data[i])
i = i + (total*.6);
if (searchKey < data[i])
i = i - (total*.6) ;
total = total*.6;
if (total < 1)
total = 2;
}
return search;
}
int main()
{
int searchKey;
int dbase[21] = {1, 4, 5, 6, 9, 14, 21, 23, 31, 42, 46, 50, 53, 57, 62, 63, 65, 74, 79, 89, 95};
cout << "List = {"; //list all the numbers for the viewer to see
for (int i = 0; i<17; i++)
{
cout << dbase[i];
if (i < 16)
cout <<", ";//thi adds a comma after every number except the last one.
}
cout <<"}" << endl;
bool quit = false;
while (!quit)
{
unsigned char inputChar = 58;
// cout << (int)inputChar;
int c = 0;
int searchKey = 0;
cout <<"Enter a search Key (or 'x' to exit): ";
cin >> inputChar >> searchKey;
if (inputChar == 'x' || inputChar =='X')
{
cout <<"Exiting..."<< endl;
quit = true;
}
else
{
int c = int(inputChar);
cout << inputChar;
// cout << Binsearch(dbase, (int) inputChar, searchKey);
}
}
}

New Topic/Question
Reply



MultiQuote





|