2012-11-12 43 views
-2

今天我的一塊代碼怪異的行爲窗戶回報的std ::矢量<std::string>返回垃圾

std::vector<std::string> getMACs() { 
    std::vector<std::string> macs; 
    for(/*something*/) { 
    char buffer[100]; 
    sprintf_s(buffer, size, "get the mac address here"); 
    std::string s = ""; 
    s.append(buffer); 
    printf("mac=%s\n", s.c_str(); //print the mac address correctly 
    macs.push_back(s); 
    } 
    return macs; 
} 

int main(int, char**) { 
    std::vector<std::string> macs = getMACs(); 
    for (size_t i = 0; i < mac.size(); i++) { 
    printf("mac=%s\n", macs[i]); //prints garbage 
    } 
} 

下,雖然在函數內部的MAC地址已正確打印,在打印無用爲主,只有我的解釋,即蘋果向量充滿垃圾字符串,但這怎麼會發生;對string.append(const char *)的調用雖然按引用傳遞,但push_back()函數應該調用字符串的拷貝構造函數,所以它不應再指向一個字符串引用,該字符串引用在離開範圍,對吧?

+3

我假設你是 「迴歸」 荷蘭國際集團的Mac?不是嗎? –

+3

請發佈一些真實,可編譯的代碼。 – jrok

+2

這不能是你的實際代碼。請提供一個可編輯的例子。 –

回答

11
printf("mac=%s\n", macs[i]); //prints garbage 

由於macs[i]std::string類型,並且printf不知道如何處理。試試這個:

printf("mac=%s\n", macs[i].c_str()); 

或者這樣:

std::cout << "mac=" << macs[i] << '\n'; 

類型安全,FTW

+0

當然我怎麼可能錯過了,非常感謝 –

6

你是返回一個字符串:

return s; 

你需要返回向量:

return macs; 

編輯你的編輯後,你的問題的可能的原因是誤用的printf。可以遍歷該載體和打印內容是這樣的:

std::vector<std::string> macs = getMACs(); 
for (std::vector<std::string>::const_iterator it = macs.begin(); it != mac.end(); ++it) { 
    std::cout << *it << "\n"; 
} 

,或者在C++ 11,

for (const auto& s : macs) { 
    std::cout << s << "\n"; 
} 
+2

我要在這裏出去,說這不是他的(失敗)代碼。 – moswald

+0

@moswald此時此刻,看起來極有可能! – juanchopanza

+0

其最可能的原因是我已經傳遞給printf參數s而不是s.c_str,我會在早上嘗試它,thnx作爲答案 –