6

I am relatively new to the C++ world. I know std::cout is used for console output in C++. But consider the following code in C :

#include<stdio.h>

int main(){
    double dNum=99.6678;
    printf("%.02lf",dNum);
    //output: 99.67
 return 0;
}

How do I achieve the similar formatting of a double type value upto 2 decimal places using cout in C++ ?

I know C++ is backward compatible with C. But is there a printf() equivalent in C++ if so, then where is it defined ?

Deanie
  • 2,316
  • 2
  • 19
  • 35
Abrar
  • 6,874
  • 9
  • 28
  • 41
  • 3
    Use `setprecision` : `std::cout << std::fixed << std::setprecision(2) << dNum;` – Hatted Rooster Oct 25 '15 at 12:16
  • 1
    Possible duplicate of [How to 'cout' the correct number of decimal places of a double value?](http://stackoverflow.com/questions/4217510/how-to-cout-the-correct-number-of-decimal-places-of-a-double-value) – mpromonet Oct 25 '15 at 13:30

9 Answers9

12

This is what you want:

std::cout << std::fixed << std::setprecision(2);
std::cout << dNum;

and don't forget to :

#include <iostream>
#include <iomanip>
mpromonet
  • 11,326
  • 43
  • 62
  • 91
vishal
  • 2,258
  • 1
  • 18
  • 27
6

There is no equivalent. It is a pain using cout for formatted output.

All suggested solutions calling setprecision and similar are awfull when using long formats.

boost::format does not support some very nice features. Incompatibilities with printf. I still use printf because it is unbeatable.

Peter VARGA
  • 4,780
  • 3
  • 39
  • 75
2

If you want to use printf like formatting you should probably use snprintf (or build an allocating variant of that on top of that). Note that sprintf requires you to be able to guarantee that the result will not overrun the buffer you have to keep defined behaviour. With snprintf on the other hand can guarantee that it will not overrun the buffer since you specifiy the maximal number of characters that will be written to the string (it will instead truncate the output).

You could even build something that can directly be fed to an ostream on top of snprintf by automatically allocate the buffer and place in an object that on destruction free that memory. This in addition with a method to feed the object to an ostream would finish it off.

struct FMT {
  char buf[2048];
  FMT(const char* fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
  }
};

inline std::ostream& operator<< (std::ostream& os, FMT const& str) { os << (const char*)str.buf; return os; }

then you use this as:

 cout << FMT("The answer is %d", 42) << endl;

If you're using the GNU libraries you could of course use printf directly since cout and stdout are the same object then. Otherwise you should probably avoid mixing stdio and iostreams as there is no guarantee that these are synchronized with each other.

Community
  • 1
  • 1
skyking
  • 13,817
  • 1
  • 35
  • 57
  • 1
    If using GCC, you can give the constructor `__attribute__ ((format (printf, 1, 2)))`, to gain some compile checking of the types. – jxh Jan 18 '18 at 22:49
2

If you really want to reuse the same formatting techniques as in C, you may use Boost::format, which does exactly that:

cout << boost::format("%.02lf") % dNum;
Daniel Strul
  • 1,458
  • 8
  • 16
  • 1
    Very good advice. Boost.Format mixes C-style flexibility, including the ability to provide the formatting dynamically, with C++ type safety. – Christian Hackl Oct 25 '15 at 14:25
2

But is there a printf() equivalent in C++ if so, then where is it defined?

There is a standards proposal P0645 to add a similar formatting facility to C++. In the meantime you can use the {fmt} library that implements this proposal and more:

#include <fmt/core.h>

int main()
  fmt::print("{:.02f}", 99.6678);
}

P0645 and {fmt} use Python-like format string syntax which is similar to printf's but uses {} as delimiters instead of %.

Also the type information is preserved so you don't need l or other noisy specifiers.

vitaut
  • 49,672
  • 25
  • 199
  • 336
0

Save your program as CPP and run it.

It runs and prints the answer.

Because C++ also has the printf() and scanf() like C.

Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
  • 3
    You should take care since `printf` prints to `stdout` which is not required to be in sync with `cout`. Using both `stdout` and `cout` is something that shouldn't be done unless you know what you're doing. – skyking Oct 25 '15 at 12:37
0

You can also use sprintf in C++ to 'print' into a string and then cout that string. This strategy leverages your experience with printf-style formatting.

nicomp
  • 4,344
  • 4
  • 27
  • 60
0

The functional equivalent of your printf() call, using std::cout, is

 std::cout << fixed << setprecision(2) << dNum;

It is necessary to #include <iomanip> and <iostream>.

The printf() equivalent in C++ is std::printf(), declared in <cstdio>.

Also, thanks to backward compatibility to C - specifically C++98 was required to maximise backward compatiblility to C89 - C's printf() declared in <stdio.h> is also available in C++. Note, however, that <stdio.h> is deprecated (tagged for removal from a future version of the C++ standard). Also, not all features of printf() introduced in C99 (the 1999 C standard) or later are necessarily supported in C++.

Peter
  • 35,646
  • 4
  • 32
  • 74
0

To output a value to the console using C++, you need the global ostream object cout and the << operator. endl is another global ostream object used as line break.

All are defined in the <iostream> header file. You can also use various formatting flags to control the presentation of the output...

#include<iostream>
using namespace std;

int main() {

    double dNum = 99.6678;

    cout << dNum;
    cout.setf(ios::scientific, ios::floatfield); // format into scientific notation
    cout << dNum;
    cout.precision(8); // change precision
    cout << dNum;

    system("pause");
    return 0;
}
vishal
  • 2,258
  • 1
  • 18
  • 27
dspfnder
  • 1,135
  • 1
  • 8
  • 13
  • `cout` writes to stdout. Often, stdout is associated with a terminal. On very rare occasions, that terminal is a console. 'cout' is "character out", and is completely unrelated to a console. – William Pursell Jul 15 '23 at 00:35