C++ equivalent of printf() or formatted output
Asked Answered
N

9

7

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 ?

Nador answered 25/10, 2015 at 12:12 Comment(2)
Use setprecision : std::cout << std::fixed << std::setprecision(2) << dNum;Stipel
Possible duplicate of How to 'cout' the correct number of decimal places of a double value?Inset
G
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>
Grayish answered 25/10, 2015 at 12:16 Comment(0)
D
8

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.

Demetri answered 3/7, 2016 at 0:11 Comment(0)
C
3

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

C++23 added a similar formatting facility to C++ called std::print:

import std;

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

On older systems you can use the {fmt} library, std::print is based on:

#include <fmt/core.h>

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

std::print and {fmt} use Python-like format string syntax which is similar to printf's except for {} delimiters instead of %.

std::print preserves the type information so it is fully type-safe and doesn't need l and similar specifiers that convey type.

Disclaimer: I'm the author of {fmt} and C++23 std::print.

Culpable answered 26/12, 2018 at 17:37 Comment(0)
K
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.

Kickstand answered 25/10, 2015 at 12:30 Comment(1)
If using GCC, you can give the constructor __attribute__ ((format (printf, 1, 2))), to gain some compile checking of the types.Suspicion
C
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;
Clayborn answered 25/10, 2015 at 12:52 Comment(1)
Very good advice. Boost.Format mixes C-style flexibility, including the ability to provide the formatting dynamically, with C++ type safety.Newel
D
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.

Design answered 25/10, 2015 at 12:16 Comment(1)
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.Kickstand
S
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.

Sphygmograph answered 25/10, 2015 at 12:18 Comment(1)
How is that better than just using printf directly?Newel
S
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++.

Shrunk answered 25/10, 2015 at 12:27 Comment(1)
printf is not deprecated. <stdio.h> is deprecated in favour of <cstdio>, that's all.Newel
P
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;
}
Procter answered 25/10, 2015 at 12:27 Comment(1)
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.Gorlicki

© 2022 - 2024 — McMap. All rights reserved.