Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this code not producing expected output?

#include<iostream>

using namespace std;

#define sp ' '

std::ostream& nl(std::ostream os)
{
    return os << '\n';
}



int main()
{
    cout << 1 << sp << 2 << nl;
    cout << 3 << sp << 4 << sp;
    cin.get();
    cout << 5 << sp << 6 << nl;
    cin.get();
    cout << 7 << sp << 8;

    return 0;
}

I’m testing out my own stream manipulator that adds newline but doesn’t flush.
I’m expecting no output until the end of program, since cout is supposed to only flush at the end of the program without endl. And also I’m expecting output to be

1 2
3 4
// newline added here and cin.get() executed adding another newline
5 6
// newline added here and cin.get() executed adding another newline
7 8

But instead I’m getting this.

1 2007818983 4  // cin.get() executed here in this line
5 600781898 //cin.get() executed here again
7 8

Why is that? And during debugging in Visual Studio 2019, is there any way to view what cout’s, cin’s or any stream’s buffer in the debugger to find out what’s going on?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is in nl function. you have to pass ostream by reference. Have a look at this code

// Pass by Ref 
std::ostream& nl(std::ostream& os){
  os << '\n';
  return os;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading