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