aboutsummaryrefslogtreecommitdiff
path: root/libbutl/prompt.cxx
blob: 2e42dd5f3f78caff733149bcccea266c3e191dc1 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// file      : libbutl/prompt.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <libbutl/prompt.hxx>

#include <iostream>

#include <libbutl/diagnostics.hxx> // diag_stream

using namespace std;

namespace butl
{
  bool
  yn_prompt (const string& prompt, char def)
  {
    // Writing a robust Y/N prompt is more difficult than one would expect.
    //
    string a;
    do
    {
      *diag_stream << prompt << ' ';

      // getline() will set the failbit if it failed to extract anything,
      // not even the delimiter and eofbit if it reached eof before seeing
      // the delimiter.
      //
      getline (cin, a);

      bool f (cin.fail ());
      bool e (cin.eof ());

      if (f || e)
        *diag_stream << endl; // Assume no delimiter (newline).

      if (f)
        throw ios_base::failure ("unable to read y/n answer from stdout");

      if (a.empty () && def != '\0')
      {
        // Don't treat eof as the default answer. We need to see the actual
        // newline.
        //
        if (!e)
          a = def;
      }
    } while (a != "y" && a != "n");

    return a == "y";
  }
}