ASKER
char buf[50];
sprintf(buf,"Pair (%d,%d) = %f\n",i,j,(double)i/j);
which are simple and easy to read, turn into this convoluted mess?std::ostringstream oss1, oss2;
oss2 << "Pair (" << i << "," << j << ") = " << std::fixed << std::setprecision(1) << (double(i)/j) << std::endl;
buf = oss2.str();
So I actually LOSE readability and conciseness in moving to std::string? This is an enormous step sideways. I have strings I need to generate with many more parameters and that would just make this code a mess. Sounds like I just need to stick to the character buffer.
auto && oss = std::ostringstream();
oss
<< "Pair (" << i << "," << j << ") = "
<< std::fixed << std::setprecision(1)
<< (double(i)/j)
<< std::endl;
auto && buf = oss.str();
auto && buf = std::string();
buf.resize(N); // where N is the size of the string buffer you need;
sprintf(&buf[0], "Pair (%d,%d) = %f\n", i, j, (double)i/j);
std::cout << buf << std::endl;
ASKER
ASKER
struct mypair
{
int x;
int y;
};
ostream operator << (ostream & out, mypair const & pair)
{
oss
<< "Pair (" <<pair.x << "," << pair.y << ") = "
<< std::fixed << std::setprecision(1)
<< (double(pair.x)/pair.y);
}
auto && oss = std::ostringstream();
auto && pair = mypair{1, 2};
oss << pair << std::endl;
pair.x = 2;
pair.y = 4;
oss << pair << std::endl;
Unfortunately, I was in the car and so unable to give an example.sorry, actually i waited some time for you to give a sample yourself.
sprintf(buf,"Pair (%d,%d) = %f\n",i,j,(double)i/j);
oss1 << "Pair (" << i << "," << j << ") = " << (double(i)/j) << "\n";
oss1 << Pair(i, j) << "\n";
#define STREAM(s) (((std::ostringstream&)(std::ostringstream() << s)).str())
std::string s = STREAM(i << "/" << j << " = " << (1.*i)/j);
if (ret != 0)
{
std::cerr << STREAM("Error " << ret << ", in SomeFunction(" << arg1 << ", " << arg2 << ")\n");
}
C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.
TRUSTED BY