N
N
Nikolay2017-09-16 19:31:47
C++ / C#
Nikolay, 2017-09-16 19:31:47

Why does the program loop if you enter a large number?

Oddly enough - an example from the book of Herbert Schildt. I could expect anything from examples, but not this:
846ab145c701445da8410d96a3315553.png
Here are the source codes for the example:

#include <iostream>
#include <cstdlib>
using namespace std;

void play(int m);

int main()
{
  int option, magic;
  magic = rand();
  do {
    cout << "1. Get new magic number\n";
    cout << "2. Play\n";
    cout << "3. Get out\n";
    
    do {
      cout << "Input your variant: ";
      cin >> option;
    } while (option < 1 || option > 3);
    
    switch (option) {
      case 1:
        magic = rand();
        break;
      case 2:
        play(magic);
        break;
      case 3:
        cout << "Goodbye!\n";
        break;
    }
  } while (option != 3);
  return 0;
}

void play(int m)
{
  int t, x;
  for (t = 0; t < 100; t++) {
    cout << "Guess the magic number: ";
    cin >> x;
    if (x == m) {
      cout << "** True **\n";
      return;
    } 
    else if (x < m) cout << "Not enough!\n";
    else cout << "A bit too much!\n";
  }
  cout << "You used every chance to guess the magic number" << "try again.";
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2017-09-16
@tryvols

The code does not handle invalid input. It will loop in the same way if you enter a letter. It is necessary to add cleaning stdin in case it is impossible to parse the input as int

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question