Home > Blockchain >  Why is this code not producing expected output?
Why is this code not producing expected output?

Time:03-14

#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?

CodePudding user response:

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;
}
  • Related