Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is cout.put() recommended over cout<< for printing characters

Tags:

c++

Background

IIRC, from Release 2.0 C++ stores single-character constants as type char and NOT int. But before Release 2.0 a statement like

cout<<'A'

was problematic as it displays the ASCII value of 'A' ie 65 whereas:

char ch='A';
cout<<ch;

would display the right value ie 'A'.

Since the problem has been rectified in Release 2.0. I believe cout.put() lost the advantage it had over cout<<.


Question

Is there any other reason for recommending cout.put() over cout<< for printing characters?

like image 500
sjsam Avatar asked Jan 05 '23 21:01

sjsam


1 Answers

There are a few differences between cout<< and cout.put, or should we say the overloaded << operator and the put method from std::basic_ostream because this is not really limited to the global instance: cout.

The << operator writes formatted output, the put method does not.

The << operator sets the failbit if the output fails, the put method does not.

Personally I would go with the << operator in almost all cases, unless I had specific needs to bypass the formatted output or not setting the failbit on error.

Using them can result in the following differences of output:

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    cout << "Character: '" << setw(10) << 'A' << setw(0) << "'" << endl;
    cout << "Character: '" << setw(10);
    cout.put('A');
    cout << setw(0) << "'" << endl;
    return 0;
}

Outputs:

Character: '         A'
Character: 'A'

See the above in action: http://ideone.com/9N0VYn

Since the put method is unformatted it does not respect the manipulator set, there might be situations where that is indeed what you intend. But since it sounds like you only want to print out the character, I would prefer the << operator, which respects the formatting.

And then there is the case of the failbit which is not being set, and that might even be more crucial.

like image 199
Tommy Andersen Avatar answered Jan 23 '23 04:01

Tommy Andersen