开发者

C++ if statement over 4 digits

im writing a program to convert a four digit octal number to a decimal number. I have to do this programs using charactes. no char rays or strings says my lecturer. does anybody no how i can do this? here is my code:

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 d开发者_StackOverflowata";
  }
  else
    cout << "Decimal form of that number: " << ((a - '0') * 512) + ((b - '0')
        * 64) + ((c - '0') * 8) + (d - '0') << endl;

  return 0;
}


This worked for me when I supplied isdigit as

bool isdigit(char digit) {
  return digit >= '0' && digit <='9';
}

and simplified the first check to

if (!isdigit(a) || !isdigit(b) || !isdigit(c) || !isdigit(d)) {
  cout << "Bad data";
} else ...


You can use cin.peek() to check the next unread character after reading a, b, c and d. If it is octal digit, then input is wrong, otherwise (even if it fails) all ok.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜