ostringstream to print float numbers in fixed notation avoiding scentific notation - c++

I'm using the following code to print float number (value is of type float):
std::ostringstream ss;
ss << std::fixed << std::setprecision(9) << value;
which works fine most the cases. However, when value is very small I'm getting things like:
2.98e-07
while I'd would expect the following (fixed notation with 9 decimal numbers):
0.0000000289
Thus, what is the way of using std::ostringstream to achive this, please?

At the end, the problem was not in the C++ program that generates the float number (that as some users have report, it is ok) but in the program that I use to beautify the output of the C++ program. Thus this question is solved (although a new one about the beautifier opens).

Related

Weird value obtained when outputting

I have this simple program that basically accepts user input and outputs it to the screen. This program works fine when I input an integer. However, when I input a string literal, this negative integer is obtained as the output. (-858993460), regardless of any string input size.
I am currently using Visual Studio 2015 Community Edition, if that matters.
Here is my code.
#include "stdafx.h"
#include <iostream>
#include <string>
int main() {
int a;
std::string b;
b = "Type something";
std::cout << b << std::endl;
std::cin >> a;
std::cout << "You said " << a << std::endl;
}
I have tried searching but to no avail. Hence, I have two questions.
1) Why is it outputting this particular negative integer when I gave it a string input?
2) Why didn't the program give me a compilation error, syntax error, or a crash? Instead, why did it go on outputting that integer?
Sorry for my bad English.
1) Why is it outputting this particular negative integer when I gave it a string input?
Because your integer was not initialized to anything, it's outputting whatever is there (primitives like int do not get default values when declared at function-level scope). Reading of the integer from the stream failed because you provided a string literal, so the integer value was not changed. If you initialize the value of the integer to 42 you'll see that it's value was unchanged when it gets printed (until C++11. After C++11 the value will become 0).
2) Why didn't the program give me a compilation error, syntax error, or a crash? Instead, why did it go on outputting that integer?
streams force the programmer to check what happened (in general*). They have implicit conversions to booleans so you can conveniently check if anything went wrong.
Try to augment your code like so:
std::cin >> a;
if (!std::cin)
{
std::cerr << "Failed to read!" << std::endl;
exit(1);
}
Demo1
*If you want std::cin to throw an exception on failure, then you can use basic_ios::exceptions to do so:
std::cin.exceptions(std::istream::badbit | std::istream::failbit);
Demo2
There is already an excellent answer. I just want to add for the second question
2) Why didn't the program give me a compilation error, syntax error,
or a crash? Instead, why did it go on outputting that integer?
error?
The compiler cannot know what the user will write. It could it could be something that can be streamed to an int but it also could be that it cannot. Thus the compiler has no chance to issue a warning/error in this situation.
crash?
If this code would cause a crash then it would be impossible to use cin to write code that cannot be crashed by malformed user input. That would make cin rather useless.
conclusion?
It is your responsibility to check if the input operation went ok and to react accordingly if it didnt.
You're storing user input in an int.
I suggest you convert the input string to int as in
std::cin >> atoi(a);

double to std::string with dynamic precisicion (without trailing zeros)

I want to convert a double value into a std::string. Currently I'm writing
return std::to_string(double_value);
But this only returns 7 digits because internally to_string() just uses std::vsnprintf with a %f format specifier (see also here).
I could now just call std::vsnprintf manually with %.15f as format specifier but this leads to trailing zeros.
My (in my eyes very obvious) goal now is to have an approach like this:
string o1 = to_string(3.14)
string o2 = to_string(3.1415926536)
assert(o1 == "3.14")
assert(o2 == "3.1415926536")
Here is a nice elaboration on trimming trailing zeros from the %.20 output but this answer is about 8 years old.
Maybe things have changed? Can I convert a double with double precision without trailing zeros in C++ today?
Solution:
Based on 2mans answer you can write a generic function like this:
template<typename T>
inline std::string tostr(T value) {
std::ostringstream s;
s.precision(std::numeric_limits<T>::digits10);
s << value;
return s.str();
}
which will behaves like desired for numeric types. Note that I took digits10 rather than max_digits10 to favor a nice decimal representation rather than more digits and trailing ..0000001
Also IMHO it's worth to add that [v][s][n]printf() together with the format string "%.15g" (rather than 'f') will also trim trailing zeros (won't work with more digits because they could not be represented with 64bit which would lead to things like a trailing '1', e.g. 3.12 -> "3.1200000000000001")
Still strange:
Maybe someone can tell me why std::to_string(double) which was introduced with C++-11 hard-codes to vsnprintf(..., "%f", ...) rather than so something like vsnprintf("%.15g") which would result in a more precise representation without affecting C code?
You can use string stream (sstring) with stream manipulators, see example below:
std::stringstream ss1;
std::stringstream ss2;
ss1.precision(15);
ss1 << 3.14;
std::cout << ss1.str()<<' '<<("3.14" == ss1.str())<<std::endl;
ss2.precision(15);
ss2 << 3.1415926536;
std::cout << ss2.str()<<' '<<("3.1415926536" == ss2.str())<<std::endl;
Or you can use boost format. Here's a link!
std::cout<<format("%.2f") % 3.14 <<std::endl;
std::cout<<format("%.10f") % 3.1415926536 <<std::endl;

Create a C++ string with given format

I'm a Objective-C dev and sometimes I have to deal with C/C++ code.
I have a function written in C++, it logs an event with name, for example, Level_12_Pack_10. I want to create a dynamic C++ string like that, then I can change level and pack numbers.
In Objective C, it's easy with some lines of code: [NSString stringwithformat] but in C++, it's a bit difficult for me.
Could anyone help me do it?
I don't think C++ supports strings with built-in changeable variables like that. It would be too over-the-top to make a class to format the string like that. Probably the closest thing you can get is to use stringstreams:
#include <sstream>
string makeMyString(int level, int pack) {
stringstream ss;
ss << "Level_" << level << "_Pack_" << pack;
return ss.str();
}
If you have a string that you need to read and change the values inside, a similar function could be used.
With c++11, it is drop dead simple just use std::to_string(level) etc to concatenate strings.
int level = 10;
int pack = 40;
std::string stuff = "Level_" + std::to_string(level) + "_Pack_" + std::to_string(pack);
//stuff is now "Level_10_Pack_40"
std::cout << stuff;

Binary to decimal conversion(positional notation method) using for_each loop c++

I'm using positional notation method convert binary to decimal and its different i guess nobody has tried it yet i guess, and in this I'm using for_each loop
Here are some steps:
store binary as string
-take out one digit at a time from string using for_each loop and do operation.
int main(void)
{
string input;
cout << "Enter string of binary digits " ;
cin >> input ;
for_each(input.begin(), input.end(),bitodec);
cout << "Decimal equivalent is " << u << endl;
system("PAUSE");
}
here is full code
There is logical error.
I am not sure what exactly it is you are asking, since you did not state a question. I presume, however, that you would like to know why you get the compiler error:
prog.cpp:13:48: error: ‘for_each’ was not declared in this scope
for_each(input.begin(), input.end(),bitodec);
(It would have been nice if this was included in the question)
You get this error because you try to use std::for_each, which was not declared in your program. It is defined in the "algorithm" header, so to fix this problem, you would have to add
#include <algorithm>
somewhere at the beginning of your file.
There are, however, some other problems with the complete code(which should really have been included in your question), for instance: Your global variable u is never modified, because you declare a new, temporary one in bitodec's if block and modify this one.
So, as Joachim Pileborg mentioned in the comments, it would be much easier(and apparently less error prone), to simply use std::stoi.
I hope this helps ;-)
As the documentation of std::bitset says:
Bitsets can be manipulated by standard logic operators and converted to and from strings and integers.
So using std::bitset is a simple way to achieve your goal. For example:
std::string bit_string = "110010";
std::bitset<8> b3(bit_string); // [0,0,1,1,0,0,1,0]
std::bitset<8> b4(bit_string, 2); // [0,0,0,0,0,0,1,0]
std::bitset<8> b5(bit_string, 2, 3); // [0,0,0,0,0,0,0,1]

Which is efficient, itoa or sprintf?

I am in the processes of building my first C++ application and choosing an efficient C++ libraries to rely on at this stage, is one of the design consideration I am looking at.
Consequently I want to convert an integer type to string and deciding on whether to use;
sprintf(string, "%d", x);
Or
Integer to ASCI
itoa(x, string);
Can anyone suggest which one of these route is efficient and possibly why?
Thanks.
They're both efficient. It's probably much more relevant to note that itoa() is not part of the C++ standard, and as such is not available in many common runtimes. (In particular, it's not part of libstdc++, so it's not available on Mac OS X or Linux.)
Don't use either of these. Use std::stringstream and so on.
std::stringstream ss;
ss << x;
ss.str(); // Access the std::string
Either way, it's quite unlikely that converting to string will be a significant part of your application's execution time.
From a pure algorithm viewpoint one can argue that itoa would be faster since sprintf has the additional cost of parsing the format descriptor string. However without benchmarking the cost of the two functions in an implementation, with a non-trivial work load, one cannot be sure.
Also this isn't apples to apples comparison since both functions aren't equivalent. sprintf can do much more formatting than itoa does, apart from the fact that the former is a standard function while the latter isn't.
Aside: If you can use C++11 you can use to_string which returns you an std::string. If you want representations other than decimal you may do this:
int i = 1234;
std::stringstream ss;
ss << std::hex << i; // hexadecimal
ss << std::oct << i; // octal
ss << std::dec << i; // decimal
std::bitset<sizeof(int) * std::numeric_limits<unsigned char>::digits> b(i);
ss << b; // binary
std::string str = ss.str();