type conversion - Why this return value? C++ int/char confusion -
using gnu gcc compiler 4.8.1. simple programme has me stuck on something. when prompted input, expects integer first value , character sec value. if instead come in character or string of text instead of integer, returns unit value of character 'u'.
can explain why case?
int main() { const double cm_per_inch = 2.54; int length = 1; char unit; cout << "please come in length followed unit (c or i): "; cin >> length; cin >> unit; if (unit == 'i') cout << length << "in == " << cm_per_inch * length << "cm\n "; else if (unit == 'c') cout << length << "cm == " << length/cm_per_inch << "in\n"; else cout << " don't know unit called " << unit << ".\n"; }
you don't initialize unit
, if input fails, contains whatever random, nonsense value happened have. none of input code tests see if succeeds or fails, yet access value of unit
either way. results if input fails unpredictable garbage.
try changing:
char unit;
to
char unit = '?';
c++ type-conversion
No comments:
Post a Comment