double b = 3.0000;
char s[20];
sprintf(s,"%f",b);


Here char s[20] is fixed it should take values however small be it.I will be happy if I get tat 20 at runtime as a varible with correct allocation size.Else for small value ter will be wastage of memory.It will allocate 20 for small values also.I want this to be working in Linux so pure c or c++ is needed.Tat means I cant use vc++.Anybody pls help!!!

Chances are, that's a local variable, and being local, the space will be reclaimed when the function returns.

If you really need to store the string result in memory for an extended period of time, then you can do what you're doing at the moment, then use malloc and strcpy to make a copy of the exact lenght required.

But be aware that allocating memory is not a zero cost thing either. It takes time to allocate memory, and there is an additional memory overhead used by the memory manager. This can be very wasteful if you allocate 1000's of really small objects like short strings.

Since this is the C++ forum, why don't you just dump sprintf() and use the standard streams?

#include <string>
#include <sstream>

int main()
{
  double b = 3.0000;
  std::string s;

  // convert double b to string s
  { std::ostringstream ss;
    ss << b;
    s = ss.str();
  }

  // do something here with s
}

The extra { } make the stringstream variable a temporary -- after you do the conversion ss doesn't exist anymore.

The advantage of using the standard streams is that you get much more flexibility when deciding how to format your output.

Hope this helps.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.