C++プログラミング:throwとcin.fail()による入力エラー処理

その買うを、もっとハッピーに。|ハピタス

整数を入力しろと言っているのに、アルファベットを入力したり、ゼロや負の数を入力した時に0より大きい数字を入力するように促す、あるいは、あまりにも巨大過ぎる数値を入力した際にプログラムを終了するコードを書きたい時、throwcin.fail()が役立つ。

前回のアラビア数字をローマ数字に変換するコードを少し改変して、0以下の整数が入力されたら1以上の整数を、アルファベットや特殊記号が入力されたら整数を入力するように再入力を促すのにwhile, if, cin.fail()を使うと目的のコードを得ることができる。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int a;
cout << "Enter an integer:\n";
cin >> a;
while (cin.fail() || a <= 0) {
  if (cin.fail()) {
    cin.clear();
    cin.ignore(6, '\n');
    cout << "Enter an integer number" << endl;
    cin >> a;
  } else if (a <= 0) {
    cout << "must be larger than 1, try again" << '\n';
    cin >> a;
  }
}

次に、入力された数値が、あまりにも巨大過ぎる場合にプログラムを終了するコードは下記のようにtry catchthrow out_of_rangeを使って書くことができる。

1
2
3
4
5
6
7
8
  try {
    if (a > 1e5) {
      throw out_of_range("too large value!!");
    }
    cout << a << " is " << introm(a) << '\n';
  } catch (out_of_range oor) {
    cout << "out of range:" << oor.what() << '\n';
  }

最終的なコードは以下のようになる。

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
#include <iostream>
#include <stdexcept>

using namespace std;

string introm(int a) {
  int intnum[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
  const char *romnum[] = {"M",  "CM", "D",  "CD", "C",  "XC", "L",
                          "XL", "X",  "IX", "V",  "IV", "I"};
  int i = 0;

  string s;
  while (a) {
    while (a / intnum[i]) {
      s += romnum[i];
      a -= intnum[i];
    }
    i++;
  }
  return s;
}

int main() {
  long long a;
  cout << "Enter an integer:\n";
  cin >> a;
  while (cin.fail() || a <= 0) {
    if (cin.fail()) {
      cin.clear();
      cin.ignore(256, '\n');
      cout << "Enter an integer number" << endl;
      cin >> a;
    } else if (a <= 0) {
      cout << "must be larger than 1, try again" << '\n';
      cin >> a;
    }
  }
  try {
    if (a > 1e5) {
      throw out_of_range("too large value!!");
    }
    cout << a << " is " << introm(a) << '\n';
  } catch (out_of_range oor) {
    cout << "out of range:" << oor.what() << '\n';
  }
  return 0;
}

このコードを実行するC++ Shell

参考サイトhttp://www.cplusplus.com/

スポンサーリンク
スポンサーリンク