Reputation:
I am appending an integer to a String reference called output inside a function. I made a String called output in another function and I passed it by reference an argument to the function. However when I try to print it I get a bunch of weird symbols ��������������������. I tried to use sstream for output but it didn't work:
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;
}
I still get creepy characters. Help!
Upvotes: 1
Views: 588
Reputation: 206697
output += id + "\t"; // this is an int
is equivalent to
output += (id + "\t");
which is equivalent to:
char const* s1 = "\t";
char const* s2 = s1 + id;
output += s2;
Unless id
is 1
or 0
, that leads to accessing memory that you are not supposed to, which causes undefined behavior.
I am guessing you want to append the string representation of id
plus "\t"
to output
. you can use:
output += std::to_string(id);
output += "\t";
Upvotes: 1