2015-05-12 41 views
0

簡單的C++程序,它爲字符串添加一個char字節。結果長度在輸出中是錯誤的。char concat to string returns wrong length

#include <iostream> 
#include <string> 

int main(){ 

    char x = 0x01; 

    std::string test; 
    test = x+"test"; 

    std::cout << "length: " << test.length() << std::endl; 
    std::cout << "test: " << test << std::endl; 
    return 0; 
} 

輸出:

length: 3 
test: est 

我前面加上一個類型字節的字符串,因爲我要通過一個插座,另一端可以發送這個數據有一個工廠,需要知道要創建的對象的類型。

+0

請參閱相關的問題:http://stackoverflow.com/questions/28957950/why-in-the-code -4561-output-is-56 – juanchopanza

回答

4
1 + "test" = "est" // 1 offset from test 

所以你正在得到正確的答案。

+---+---+---+---+---+ 
| t | e | s | t | \0| 
+---+---+---+---+---+ 
    +0 +1 +2 +3 +4 

你想要的可能是:

std::string test; 
test += x; 
test += "test"; 
+0

我想實際將字符添加到字符串中,而不是將指針前移一個。 – user249806

0

你是不是有std::string串聯一個char,你以爲你是。這是因爲"test"實際上是一個文字const char*,所以當您將x添加到它時,您只是在進行指針算術。您可以更換

test = x + "test"; 

test = std::to_string(x) + "test"; 

然後你output will be

length: 5 
test: 1test 
+0

'std :: to_string()'在C++ 11中是新的。對於早期版本的C++,您可以使用'std :: string(&x,1)'代替。 –

+0

@RemyLebeau會做不同的事情 – sehe