下面一段代碼:`C++中的unsigned char無效?
unsigned char agevalue;
cout<<"what is your age?"<< endl;
cin >> agevalue;
cout<<"your age is:"<< agevalue <<endl;`
削減值大於9,只留下第一個數字。 這可能是什麼原因?
下面一段代碼:`C++中的unsigned char無效?
unsigned char agevalue;
cout<<"what is your age?"<< endl;
cin >> agevalue;
cout<<"your age is:"<< agevalue <<endl;`
削減值大於9,只留下第一個數字。 這可能是什麼原因?
如果您正在尋找在數量上拉,你需要使用正確的數據類型:
unsigned short ageValue = 0;
cout << "What is your age?" << endl;
cin >> ageValue;
cout << "Your age is " << agevalue << endl;
如果你真的想年齡值存儲在一個字節大小整數(而不是半字):
unsigned char ageValue = 0;
unsigned short inputValue = 0;
cout << "What is your age?" << endl;
cin >> inputValue;
ageValue = static_cast<unsigned char>(inputValue);
cout << "Your age is " << static_cast<unsigned short>(agevalue) << endl;
你應該經常檢查你的輸入是否成功,例如'if(std :: cin >> agevalue){do_something_with(agevalue); }'第一個'std :: endl'肯定是不必要的,並且使用''\ n''來避免重複刷新。 –