Std :: string and format string

I found below code via google. It almost does what I want it to do, except that it doesn't specify a way to specify precision, such as "%. * F" in C-type format strings. Moreover, it contains nothing but 5 decimal places. Should I stick to C and snprintf lines?

#include <string>
#include <sstream>
#include <iostream>

template <class T>
std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
{
  std::ostringstream oss;
  oss << f << t;
  return oss.str();
}

int main()
{
  std::cout<<to_string<double>(3.1415926535897931, std::dec)<<std::endl;
  return 0;
} 

      

+2


source to share


4 answers


You want to use a std::setprecision

manipulator:



int main()
{
    std::cout << std::setprecision(9) << to_string<long>(3.1415926535897931, std::dec)
              << '\n';
    return 0;
}

      

+2


source


C ++ will not be successful if it cannot do something C can.

You need to check out manipulators .



If you want C-style formatting (which I prefer, it's more concise) take a look at Boost.Format .

+2


source


Have you looked at Boost :: format ?

Edit: It's not really clear what you want. If you just want to write a string, with formatting, you can use normal string manipulators. If you want to use printf-style format strings, but are type-safe, Boost :: format can / will do that.

+1


source


Taking an almost correct answer (note that std :: dec is redundant in this simple case):

int main()
{
  std::cout << std::setprecision(9) << std::dec << 3.1415926535897931 << std::endl;
  return 0;
}

      

However, if you want the to_string function to behave as desired, it's a little more complicated. You need to pass setprecision(9)

to a function to_string<T>

and it doesn't accept arguments of this type. You need a boilerplate version:

template <class T, class F>
std::string to_string(T t, F f)
{
  std::ostringstream oss;
  oss << f << t;
  return oss.str();
}
int main()
{
  std::cout << to_string<double>(3.1415926535897931, std::setprecision(9)) << std::endl;
  return 0;
}

      

This works because you don't really need std :: dec in to_string. But if you needed to go through more manipulators, a simple solution is to add template <class T, class F1, class F2> std::string to_string(T t, F1 f1, F2 f2)

, etc. It doesn't technically scale very well, but it will be so rare that you probably don't need it at all.

+1


source







All Articles