I am working on application which works on various flavors of Unix and Windows 32bit and 64bit OS.
I am using long double
data type, When I do sprintf()
and used long double
with %lf
in it then it works fine with windows does not give any kind of error, however on Solaris platform it gives core dump.
Sample code for the same issue is as following.
void main(){ string size = "16622"; string sizeFact = "20"; long long sizeLongLong = strtoll(size); int factInt = atoi(sizeFact); long double sizeLongDouble = (long double) sizeLongLong/pow(2, factInt); char buf[512]; sprintf(buf, "%.3lf %s", sizeLongDouble, "str"); }
As mentioned above code works fine on windows 32bit and 64bit however for sprintf it gives me core on Solaris.
I tried type casting in sprintf it worked fine.
sprintf(buf, "%.3lf %s", (double) sizeLongDouble, "str");
What is the format specifier for long double
?
What is the mistake I am making here, am I using wrong format specifier because of which it is giving core?
Why do I need to type cast one more time in sprintf()?
Long Int Format Specifier %ld The %ld format specifier is implemented for representing long integer values. It is implemented with the printf() function for printing the long integer value stored in the variable.
We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.
So when you are using printf and scanf function in your C/C++ code to print a long double as output and to take some input as a long double, it will always give you wrong result. If you want to use long double then you have to use " __mingw_printf " and " __mingw_scanf " function instead of printf and scanf.
%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double ) and both of them use %f .
For long double
you should use format "%Lf"
. Formatting with small L (i.e. "%lf"
) have no effect on POSIX systems (see the specification).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With