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;
}
我仍然得到令人毛骨悚然的字符。幫幫我!
您需要在合併之前將數字轉換爲字符串。 'output + = std :: to_string(id)+「\ t」;'。 –
'output + = id +「\ t」;'不符合您的想法。 –
'id +「\ t」'看起來像是一個整數和(會衰減)一個指針,從而導致(可能表現爲未定義的行爲)指向隨機存儲器的指針,字符串文字存儲在內存中。你可能不想試圖將從該內存位置開始的字符串追加到'output'。 – Hurkyl