[英]Printing character after addition as string in C++
我試圖在 C++ 中將'd'
打印為字符串。
string s = to_string((char)('a'+ 3));
cout << s << endl;
預期輸出: "d"
實際輸出: "100"
我無法理解這種行為。 任何幫助將不勝感激。
std::to_string
是一個將整數或浮點值轉換為字符串的函數。 你不應該在這種情況下使用它。
簡單使用
std::cout << 'a' + 3 << std::endl;
或者
char c = 'a' + 3;
std::cout << c << std::endl;
或者,如果您真的希望將結果保存為字符串:
std::string s = std::string{'a' + 3};
std::cout << s << std::endl;
你需要的是
std::string s( 1, 'a'+ 3 );
或者
std::string s;
s += 'a'+ 3;
或者例如像
std::string s( 1, 'a' );
s.back() += 3;
(有幾種方法可以得到預期的結果)
至於這個聲明
string s = to_string((char)('a'+ 3));
然后表達式 ( char )('a' + 3 ) 被隱式轉換為int
類型(由於整數提升和所選重載函數 std::to_string 的參數類型),在調用后表示為字符串std::to_string 的..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.