2013-09-25 94 views
1

下面一段代碼:`C++中的unsigned char無效?

unsigned char agevalue; 
cout<<"what is your age?"<< endl; 
cin >> agevalue; 
cout<<"your age is:"<< agevalue <<endl;` 

削減值大於9,只留下第一個數字。 這可能是什麼原因?

+0

你應該經常檢查你的輸入是否成功,例如'if(std :: cin >> agevalue){do_something_with(agevalue); }'第一個'std :: endl'肯定是不必要的,並且使用''\ n''來避免重複刷新。 –

回答

10

儘管在某些情況下,unsigned char被視爲整數,但主要用於表示個別字符。因此,您的代碼只是讀取第一位數字。如果要讀取數字,則需要使用非整數類型之一,例如int(如果需要整數,這應該是您的默認選擇)。

+0

也就是說,如果輸入'123','agevalue'將存儲表示*字符*''1''('49')的ASCII值。然後打印出*字符*''1''。 – BoBTFish

+0

有趣,因爲他們說char是另一種整數類型,但也可以帶字母 – Bak1139

+1

在很多方面都是這樣。但從標準庫的部分角度來看,特別是那些與輸入/輸出有關的部分,它的處理方式是不同的。 – BoBTFish

5

因爲你正在讀一個字符而不是一個整數。

+0

但char也用於整數 – Bak1139

+0

但'char'的'''重載被寫入來讀取字符,即使您可以將任意整數存儲在char中。 –

+2

請知道一個字符內部由一個整數表示,但其類型不是整數。 – Sadique

0

如果您正在尋找在數量上拉,你需要使用正確的數據類型:

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; 
相關問題