猜数字

c++代码

# include
# include
# include
using namespace std;
class Games 
{
 public: 
  int middle;
  Games() { middle = rand()%101; }
  void play() 
  {
   cout << "猜一个0-100之间的数" << endl;
   int k = middle + 1, i = 0; string s;
   while (k!=middle)
   {
    i++;
    cout << "第" << i << "次猜" << ",请输入一个整数:";
    cin >> s;
    if (s.length() > 1)
     if (s[0] == '0'||s.find('.')) { cout << "非法整数" << endl; continue; }
    try{k = stoi(s, 0, 10);}
    catch (invalid_argument&) { cout << "非法整数" << endl; continue; }
    catch (out_of_range&) { cout << "超出int范围" << endl; continue; }
    catch (...) { cout << "输入有误" << endl; continue; }
    if (k > middle) cout << "过大" << endl;
    else if (k < middle) cout << "过小" << endl;
    else cout << "猜对了,这个数字是" << k << endl;
   }
  }
};
int main()
{
 srand(time(0));
 Games a;
 a.play();
}

你可能感兴趣的:(猜数字)