問題描述
將 2 位整數分配給 char 變量 (Assigning a 2 digit integer to a char variable)
我在學校做一個簡單的作業,其中包括將一個兩位整數 (<100) 分配給一個 char 變量。我正在使用 Xcode 9.2。我應該能夠做到這一點,Xcode 沒有抱怨。然而,當我嘗試將變量 cout
到控制台時,它返回 _
代替變量
This on a .cpp 文件在一個普通的
命令行工具
項目中。
char desired_score;
desired_score = 95;
cout << "I will work hard to get a grade of " << desired_score << " in this course!\n";
此代碼產生:
I will work hard to get a grade of _ in this course!
如果我將值分配給單個數字,它輸出就好了。所以我能夠編寫一個解決方法,我只需將變量值從 '9'
重新分配給 '5'
並使用兩個不同的 cout
語句.
有人知道為什麼會這樣嗎?這是家庭作業的一部分,我的教科書說這在 C++ 中應該是可能的。這是 Xcode 的特性嗎?
提前致謝。
參考解法
方法 1:
When you write a char
to a stream, it's assumed that you wish to write an actual character instead of its integer value. To output an integer, cast it instead:
cout << "I will work hard to get a grade of "
<< static_cast<int>(desired_score)
<< " in this course!\n";
方法 2:
The reason this is happening is because the ascii code for _ (underscore) is 95. A simple fix would be to use either a string, an int, or a short instead of a char.
Edit: It works for single digits because you used a character literal, NOT because characters are also bytes in c++. That was my mistake.
參考文件