2016-09-29 263 views
1

我只是在審查我的C++。我試圖做到這一點:cout和字符串連接

#include <iostream> 

using std::cout; 
using std::endl; 

void printStuff(int x); 

int main() { 
    printStuff(10); 
    return 0; 
} 

void printStuff(int x) { 
    cout << "My favorite number is " + x << endl; 
} 

該問題發生在printStuff函數。當我運行它時,輸出中將省略「我的最愛號碼」中的前10個字符。輸出是「電子號碼是」。這個數字甚至沒有出現。

解決這個問題的方法是做

void printStuff(int x) { 
    cout << "My favorite number is " << x << endl; 
} 

我想知道什麼計算機/編譯器做幕後。

回答

3

這是簡單的指針算術。字符串文字是一個數組或將作爲指針呈現。你給指針加10,告訴你要從第11個字符開始輸出。

沒有+運算符會將數字轉換爲字符串並將其連接到char數組。

0

在這種情況下,+重載運算符不是連接任何字符串,因爲x是一個整數。在這種情況下,輸出會移動右值。所以前10個字符不會被打印。檢查this參考。

,如果你會寫

cout << "My favorite number is " + std::to_string(x) << endl; 

,將工作

0

增加或增加一個字符串不增加它包含的價值,但它的地址:

  • 這不是問題msvc 2015或cout,但它的內存後移/前進: 向你證明cout是無辜的:

    #include <iostream> 
    using std::cout; 
    using std::endl; 
    
    int main() 
    { 
    
        char* str = "My favorite number is "; 
        int a = 10; 
    
        for(int i(0); i < strlen(str); i++) 
        std::cout << str + i << std::endl; 
    
        char* ptrTxt = "Hello"; 
        while(strlen(ptrTxt++)) 
         std::cout << ptrTxt << std::endl; 
    
        // proving that cout is innocent: 
    
        char* str2 = str + 10; // copying from element 10 to the end of str to stre. like strncpy() 
        std::cout << str2 << std::endl; // cout prints what is exactly in str2 
    
        return 0; 
    }