C ++ if语句超过4位数字

问题描述

| 我正在编写一个程序,将四位数的八进制数字转换为十进制数字。我必须使用字符进行此程序。我的讲师说,没有字符或字符串。没有人没有我该怎么做?这是我的代码
int main() {

  char a = 0;
  char b = 0;
  char c = 0;
  char d = 0;

  cout << \"Enter 4 digit octal number \";
  cin >> a >> b >> c >> d;
  if (a - \'0\' > 7 || b - \'0\' > 7 || c - \'0\' > 7 || d - \'0\' > 7 || !isdigit(a)
      || !isdigit(b) || !isdigit(c) || !isdigit(d)) {
    cout << \"Bad data\";
  }
  else
    cout << \"Decimal form of that number: \" << ((a - \'0\') * 512) + ((b - \'0\')
        * 64) + ((c - \'0\') * 8) + (d - \'0\') << endl;

  return 0;
}

解决方法

当我提供
isdigit
作为
bool isdigit(char digit) {
  return digit >= \'0\' && digit <=\'9\';
}
并将第一张支票简化为
if (!isdigit(a) || !isdigit(b) || !isdigit(c) || !isdigit(d)) {
  cout << \"Bad data\";
} else ...
,读取
a
b
c
和ѭ8after后,可以使用
cin.peek()
检查下一个未读字符。如果是八位数字,则输入错误,否则(即使失败)也可以。