2016-09-29 214 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; 
    }