Beginner Exercises: Bracketing Search

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
int main()
{
  std::cout<<"Let pc to guess.\n";
  int guess, upper=100, lower=1;
  char judge;
  while(true)
    {
      guess=(upper+lower)/2;
      std::cout<<guess<<"?(y/n) ";
      std::cin.get(judge);
      if(judge=='y'|| judge=='Y')break;
      if(judge!='n'&& judge!='N')std::cout<<"Assuming a wrong guess.\n";
      while(std::cin.get()!='\n')continue; //get rid of input                   
      std::cout<<"High(h) or Low(l)? ";
      while(true)
        {
          std::cin.get(judge);
          if(judge=='h'|| judge=='H'){upper=guess;break;}
          else if(judge=='l'||judge=='L'){lower=guess;break;}
          else std::cout<<"Only h or l accepted, again plese:";
      while(std::cin.get()!='\n')continue;
        }
      while(std::cin.get()!='\n')continue;
    }
}

This is my try for the fifth problem in beginner exercises. The problem seems ok, but I found
it is really annoying to deal with the assumed "stupid users input". Any better ideas? I am a
newbie to C++, so any comments are welcomed:)
Last edited on
Not about your question,but you can use cout if you add this :

1
2
3
4
5
6
7
8
9
#include <......>
using namespace std; //    <--no need std::cout

int main()
{
...........
cout<<"No user no invalid input.";
.............
}
how to deal with stupid user inputs and/or C++ I/O in general:
1. http://www.cplusplus.com/forum/articles/6046/
2. http://www.augustcouncil.com/~tgibson/tutorial/iotips.html
oldnewbie, I just keep std:: to remind me those are in std. BTW, how to keep the code area smaller like yours?
Mine seems too big.
matsom, thanks for the links.
Last edited on
Line 14 of your code has a ton of spaces which is makes the page stretch.
Topic archived. No new replies allowed.