2

While using the boolean check for the int num this loop doesn't work. The lines after it go unrecognized. Enter and integer like 60 and it just closes. Did I use isdigit wrong?

int main()
{
    int num;
    int loop = -1;

    while (loop ==-1)
    {
        cin >> num;
        int ctemp = (num-32) * 5 / 9;
        int ftemp = num*9/5 + 32;
        if (!isdigit(num)) {
            exit(0);  // if user enters decimals or letters program closes
        }

        cout << num << "°F = " << ctemp << "°C" << endl;
        cout << num << "°C = " << ftemp << "°F" << endl;

        if (num == 1) {
            cout << "this is a seperate condition";
        } else {
            continue;  //must not end loop
        }

        loop = -1;
    }
    return 0;
}
RBerteig
  • 41,948
  • 7
  • 88
  • 128
TwoRoses
  • 51
  • 3
  • 7

3 Answers3

3

When you call isdigit(num), the num must have the ASCII value of a character (0..255 or EOF).

If it's defined as int num then cin >> num will put the integer value of the number in it, not the ASCII value of the letter.

For example:

int num;
char c;
cin >> num; // input is "0"
cin >> c; // input is "0"

then isdigit(num) is false (because at place 0 of ASCII is not a digit), but isdigit(c) is true (because at place 30 of ASCII there's a digit '0').

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
littleadv
  • 20,100
  • 2
  • 36
  • 50
3

isdigit only checks if the specified character is a digit. One character, not two, and not an integer, as num appears to be defined as. You should remove that check entirely since cin already handles the validation for you.

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

If you're trying to protect yourself from invalid input (outside a range, non-numbers, etc), there are several gotchas to worry about:

// user types "foo" and then "bar" when prompted for input
int num;
std::cin >> num;  // nothing is extracted from cin, because "foo" is not a number
std::string str;
std::cint >> str;  // extracts "foo" -- not "bar", (the previous extraction failed)

More detail here: Ignore user input outside of what's to be chosen from

Community
  • 1
  • 1
Tim
  • 8,912
  • 3
  • 39
  • 57