Printing double without losing precision

It’s not correct to say “floating point is inaccurate”, although I admit that’s a useful simplification. If we used base 8 or 16 in real life then people around here would be saying “base 10 decimal fraction packages are inaccurate, why did anyone ever cook those up?”. The problem is that integral values translate exactly … Read more

In Java, how can I redirect System.out to null then back to stdout again?

Man, this is not so good, because Java is cross-platform and ‘/dev/null’ is Unix specific (apparently there is an alternative on Windows, read the comments). So your best option is to create a custom OutputStream to disable output. try { System.out.println(“this should go to stdout”); PrintStream original = System.out; System.setOut(new PrintStream(new OutputStream() { public void … Read more

When should I use string instead of stringstream?

I don’t know which one will be faster, but if I had to guess I’d say your second example is, especially since you’ve called the reserve member function to allocate a large space for expansion. If you’re only concatenating strings use string::append (or string::operator+=). If you’re going to convert numbers to their string representation, as … Read more

Include of iostream leads to different binary

Each translation unit that includes <iostream> contains a copy of ios_base::Init object: static ios_base::Init __ioinit; This object is used to initialize the standard streams (std::cout and its friends). This method is called Schwarz Counter and it ensures that the standard streams are always initialized before their first use (provided iostream header has been included). That … Read more

Find all substring’s occurrences and locations

string str,sub; // str is string to search, sub is the substring to search for vector<size_t> positions; // holds all the positions that sub occurs within str size_t pos = str.find(sub, 0); while(pos != string::npos) { positions.push_back(pos); pos = str.find(sub,pos+1); } Edit I misread your post, you said substring, and I assumed you meant you … Read more

vs. vs. “iostream.h”

In short: iostream.h is deprecated—it is the original Stroustrup version. iostream is the version from the standards committee. Generally, compilers point them both to the same thing, but some older compilers won’t have the older one. In some odd cases, they will both exist and be different (to support legacy code) and you then must … Read more