將 2 位整數分配給 char 變量 (Assigning a 2 digit integer to a char variable)


問題描述

將 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.

(by MagicGATpaddyAggs123)

參考文件

  1. Assigning a 2 digit integer to a char variable (CC BY‑SA 2.5/3.0/4.0)

#XCode #C++ #char






相關問題

卸載 xcode 4.5 (iOS 6) (Uninstall xcode 4.5 (iOS 6))

uitextview 字體不隨 fontWIthName 改變 (uitextview font not changing with fontWIthName)

如何將以下行添加到我的 plist 文件中? (How can I add the following lines to my plist file?)

XCode 4.6 顯示方法 + (void)beginAnimations:(NSString *)animationID context:(void *)context; 的內存洩漏警告 (XCode 4.6 shows a warning of memory leak for method + (void)beginAnimations:(NSString *)animationID context:(void *)context;)

iPhone SDK:檢查 UITableView 中每個對象的 ID 號並相應地更改徽章號 (iPhone SDK: Checking the ID number for each object in a UITableView and change the badge number accordingly)

畫面區域的選擇 (Selection of screen area)

如何更改主視圖是基於導航的應用程序! (how to change main view is navigation based app!)

Cocos2d 中的粒子碰撞檢測 (Collision detection with particles in Cocos2d)

Xcode Playground 只能部分運行 (Xcode Playground can only run partially)

如何為collectionviewcell的刪除自定義動畫? (How to custom animation for collectionviewcell's deletion?)

將 2 位整數分配給 char 變量 (Assigning a 2 digit integer to a char variable)

Xcode 12.5 (12E262) 在將 .scn 文件添加到 ARKit 項目後,“Command CodeSign 失敗,退出代碼為非零” (Xcode 12.5 (12E262) "Command CodeSign failed with a nonzero exit code" after a .scn file added to ARKit project)







留言討論