2017-03-05 54 views
1

我在一個函數裏面添加一個整數給一個叫做輸出的字符串引用。我在另一個函數中創建了一個名爲output的String,並且通過引用該函數的參數來傳遞它。但是,當我嘗試打印它時,我收到了一堆奇怪的符號 。我試圖用sstream輸出,但它沒有工作:如何打印一個字符串裏面有整數C++

Student.cc

void Student::makeString(string& output){ 
    output += fname + "\t"; // this is a string 
    output += lname + "\t"; // this is a string 
    output += id + "\t"; // this is an int 
} 

IO.cc

void IO::printInfo(Student& student){ 
    string output = ""; 
    student.makeString(output); 

    // doesnt work 
    cout << output << endl; 

    // doesn't work 
    stringstream ss; 
    ss << output; 
    cout << ss.str() << endl; 
} 

我仍然得到令人毛骨悚然的字符。幫幫我!

+0

您需要在合併之前將數字轉換爲字符串。 'output + = std :: to_string(id)+「\ t」;'。 –

+3

'output + = id +「\ t」;'不符合您的想法。 –

+1

'id +「\ t」'看起來像是一個整數和(會衰減)一個指針,從而導致(可能表現爲未定義的行爲)指向隨機存儲器的指針,字符串文字存儲在內存中。你可能不想試圖將從該內存位置開始的字符串追加到'output'。 – Hurkyl

回答

1
output += id + "\t"; // this is an int 

相當於

output += (id + "\t"); 

這相當於:

char const* s1 = "\t"; 
char const* s2 = s1 + id; 
output += s2; 

除非id10,導致訪問,你是不是應該內存,這會導致未定義的行爲。

我猜你想要附加id加上"\t"output的字符串表示形式。您可以使用:

output += std::to_string(id); 
output += "\t";