mystery segmentation fault involving template

N

nandor.sieben

The following program causes a segmentation fault. If I break the
print line at the end into two separate print statement then there is
no segmentation fault. What is the problem? I am compiling it on
Ubuntu Gutsy.

using namespace
std;

#include
<iostream>
#include
<sstream>

template < class T > string all2string (T in, int
i)
{
stringstream
s;
s <<
in;
string
ss;
ss = s.str
();
while (ss.length () <
i)
ss = "0" +
ss;
return
ss;
}

typedef
struct
{
int
move;
int
depth;
}
Tdata;

string
Tdata2string (const Tdata &
data)
{
string s
=
all2string (data.depth, 0) + " " + all2string (data.move, 0) + "
";
return
s;
}

ostream & operator << (ostream & os, const Tdata &
data)
{
string s = Tdata2string
(data);
os <<
s;
}

main
()
{
Tdata
dat;
dat.depth =
0;
dat.move =
-1;


cout << dat <<"data
\n";
}
 
G

Greg Herlihy

The following program causes a segmentation fault. If I break the
print line at the end into two separate print statement then there is
no segmentation fault. What is the problem? I am compiling it on
Ubuntu Gutsy.
...

.
ostream & operator <<(ostream& os, const Tdata& data)
{
  string s = Tdata2string(data);
  os << s;
}

The last line of your operator<<() routine (above) should be

return os << s;

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top