How can I see cout output in a non-console application? - c++

It seems rather tedious to output to debug window. Where can I find cout output if I am writing a non-console information ?
Like:
double i = a / b;
cout << b << endl;//I want to check out whether b is zero. It seems the output cannot be found anywhere.

The question is very clear. How use std::cout to debug a non-console application in Visual Studio.
The answer is very clear: you cannot. That is, Visual Studio does not support std::cout as debug tool for non-console applications.
This is a serious limitation of Visual Studio, probably a failure to meet the C++ standard even. I find it very sad to see disinformative "answers" here trying to hide this defect of their precious Visual Studio.

For a Windows solution, you can allocate a console, and bind cout/cin to it. For example:
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
Documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681944%28v=vs.85%29.aspx

SOLUTION: This answer solves the question and allows you to redirect console output to the Visual Studio Output window.
First we need a class that overrides the default cout string stream:
class dbg_stream_for_cout
: public std::stringbuf
{
public:
~dbg_stream_for_cout() { sync(); }
int sync()
{
::OutputDebugStringA(str().c_str());
str(std::string()); // Clear the string buffer
return 0;
}
};
dbg_stream_for_cout g_DebugStreamFor_cout;
Then, somewhere you want to "activate" writing to the VS output window:
std::cout.rdbuf(&g_DebugStreamFor_cout); // Redirect std::cout to OutputDebugString!

To output a string to the debug console, use OutputDebugStringA. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa363362%28v=vs.85%29.aspx
To output variable values to the debug console, using std::ostringstream, the send the string to OutputDebugStringA.
Excessive output statements will cause the program to severly slow down. However, it is a good technique to catch things the debugger has a problem with, such as the actual child members when playing with base pointers.

I'd like to give my 2 cents.
Given that the maybe is a VS issue about compliancy with the C++ standard or that we could use OutputDebugStringA, if you cannot modify your code base you may like the idea of simply redirect the std::cout to something else, like a file.
So without changing your code base you can do something like suggested here:How to redirect cin and cout to files?
Condensed:
add the include #include <fstream>
at the beginning of your app, in some init, before logging you can use:
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
the at the end of your app/logging:
std::cout.rdbuf(coutbuf); //reset to standard output again
Hope this may help someone, Kudos to Nawaz that provided the answer in the other thread.

Instead of using cout, create a log file and write anything you want into it.
Edit:
Use this simple code for writing to a log file.
ofstream log;
log.open ("log.txt");
log << "Writing this to a file.\n";
log.close();

You can use .Net functions such as System::Diagnostics::Debug::WriteLine("your message"). You can even add a condition to print only during the debug mode and not in the release mode. For example:
#ifdef DEBUG
System::Diagnostics::Debug::WriteLine("your message");
#endif

Yes, indeed, it's annoying.
Here's how I do it :
#define DBOUT( s ) \
{ \
std::wostringstream os_; \
os_ << s; \
OutputDebugStringW( os_.str().c_str() ); \
}
// example : DBOUT("some text " << some_variable << " some more text" << some_other_varaible << "\n");

Related

I have a problem with output in C++, two last prints do not work [duplicate]

Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").
Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.
Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.
std::cout << "Hello" << std::endl;
std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:
std::cout.flush();
std::cout won't work on GUI apps!
Specific to MS Visual Studio:
When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.
To effectively disable buffering you can call this:
std::setvbuf(stdout, NULL, _IONBF, 0);
Alternatively, you can call your program and disable output buffering in the command line:
stdbuf -o 0 ./yourprogram --yourargs
Keep in mind this is not usually done for performance reasons.
It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).
You can do one of these things:
flush std::cout explicitly:
std::cout << "test" << std::flush; // std::flush is in <iostream>
std::cout << "test";
std::cout.flush(); // explicitly flush here
std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").

I can't get the ofstream function to work

Hello and sorry if the answer is clear to those out there. I am still fairly new to programming and ask for some guidance.
This function should write just one of the three string parameters it takes in to the txt file I have already generated. When I run the program the function seems to work fine and the cout statement shows the info is in the string and does get passes successfully. The issue is after running the program I go to check the txt file and find it is still blank.
I am using C++17 on visual studio professional 2015.
void AddNewMagicItem(const std::string & ItemKey,
const std::string & ItemDescription,
const std::string &filename)
{
const char* ItemKeyName = ItemKey.c_str();
const char* ItemDescriptionBody = ItemDescription.c_str();
const char* FileToAddItemTo = filename.c_str();
std::ofstream AddingItem(FileToAddItemTo);
std::ifstream FileCheck(FileToAddItemTo);
AddingItem.open(FileToAddItemTo, std::ios::out | std::ios::app);
if (_access(FileToAddItemTo, 0) == 0)
{
if (FileCheck.is_open())
{
AddingItem << ItemKey;
std::cout << ItemKey << std::endl;
}
}
AddingItem.close(); // not sure these are necessary
FileCheck.close(); //not sure these are necessary
}
This should print out a message onto a .txt file when you pass a string into the ItemKey parameter.
Thank you very much for your help and again please forgive me as I am also new to stackoverflow and might have made some mistakes in formatting this question or not being clear enough.
ADD ON: Thank you everyone who has answered this question and for all your help. I appreciate the help and would like to personally thank you all for your help, comments, and input on this topic. May your code compile every time and may your code reviews always be commented.
As mentioned by previous commenters/answerers, your code can be simplified by letting the destructor of the ofstream object close the file for you, and by refraining from using the c_str() conversion function.
This code seems to do what you wanted, on GCC v8 at least:
#include <string>
#include <fstream>
#include <iostream>
void AddNewMagicItem(const std::string& ItemKey,
const std::string& ItemDescription,
const std::string& fileName)
{
std::ofstream AddingItem{fileName, std::ios::app};
if (AddingItem) { // if file successfully opened
AddingItem << ItemKey;
std::cout << ItemKey << std::endl;
}
else {
std::cerr << "Could not open file " << fileName << std::endl;
}
// implicit close of AddingItem file handle here
}
int main(int argc, char* argv[])
{
std::string outputFileName{"foobar.txt"};
std::string desc{"Description"};
// use implicit conversion of "key*" C strings to std::string objects:
AddNewMagicItem("key1", desc, outputFileName);
AddNewMagicItem("key2", desc, outputFileName);
AddNewMagicItem("key3", desc, outputFileName);
return 0;
}
Main Problem
std::ofstream AddingItem(FileToAddItemTo);
opened the file. Opening it again with
AddingItem.open(FileToAddItemTo, std::ios::out | std::ios::app);
caused the stream to fail.
Solution
Move the open modes into the constructor (std::ofstream AddingItem(FileToAddItemTo, std::ios::app);) and remove the manual open.
Note that only the app open mode is needed. ofstream implies the out mode is already set.
Note: If the user does not have access to the file, the file cannot be opened. There is no need to test for this separately. I find testing for an open file followed by a call to perror or a similar target-specific call to provide details on the cause of the failure to be a useful feature.
Note that there are several different states the stream could be in and is_open is sort of off to the side. You want to check all of them to make sure an IO transaction succeeded. In this case the file is open, so if is_open is all you check, you miss the failbit. A common related bug when reading is only testing for EOF and winding up in a loop of failed reads that will never reach the end of the file (or reading past the end of the file by checking too soon).
AddingItem << ItemKey;
becomes
if (!(AddingItem << ItemKey))
{
//handle failure
}
Sometimes you will need better granularity to determine exactly what happened in order to properly handle the error. Check the state bits and possibly perror and target-specific
diagnostics as above.
Side Problem
Opening a file for simultaneous read and write with multiple fstreams is not recommended. The different streams will provide different buffered views of the same file resulting in instability.
Attempting to read and write the same file through a single ostream can be done, but it is exceptionally difficult to get right. The standard rule of thumb is read the file into memory and close the file, edit the memory, and the open the file, write the memory, close the file. Keep the in-memory copy of the file if possible so that you do not have to reread the file.
If you need to be certain a file was written correctly, write the file and then read it back, parse it, and verify that the information is correct. While verifying, do not allow the file to be written again. Don't try to multithread this.
Details
Here's a little example to show what went wrong and where.
#include <iostream>
#include <fstream>
int main()
{
std::ofstream AddingItem("test");
if (AddingItem.is_open()) // test file is open
{
std::cout << "open";
}
if (AddingItem) // test stream is writable
{
std::cout << " and writable\n";
}
else
{
std::cout << " and NOT writable\n";
}
AddingItem.open("test", std::ios::app);
if (AddingItem.is_open())
{
std::cout << "open";
}
if (AddingItem)
{
std::cout << " and writable\n";
}
else
{
std::cout << " and NOT writable\n";
}
}
Assuming the working directory is valid and the user has permissions to write to test, we will see that the program output is
open and writable
open and NOT writable
This shows that
std::ofstream AddingItem("test");
opened the file and that
AddingItem.open("test", std::ios::app);
left the file open, but put the stream in a non-writable error state to force you to deal with the potential logic error of trying to have two files open in the same stream at the same time. Basically it's saying, "I'm sorry Dave, I'm afraid I can't do that." without Undefined Behaviour or the full Hal 9000 bloodbath.
Unfortunately to get this message, you have to look at the correct error bits. In this case I looked at all of them with if (AddingItem).
As a complement of the already given question comments:
If you want to write data into a file, I do not understand why you have used a std::ifstream. Only std::ofstream is needed.
You can write data into a file this way:
const std::string file_path("../tmp_test/file_test.txt"); // path to the file
std::string content_to_write("Something\n"); // content to be written in the file
std::ofstream file_s(file_path, std::ios::app); // construct and open the ostream in appending mode
if(file_s) // if the stream is successfully open
{
file_s << content_to_write; // write data
file_s.close(); // close the file (or you can also let the file_s destructor do it for you at the end of the block)
}
else
std::cout << "Fail to open: " << file_path << std::endl; // write an error message
As you said being quite new to programming, I have explicitly commented each line to make it more understandable.
I hope it helps.
EDIT:
For more explanation, you tried to open the file 3 times (twice in writing mode and once in reading mode). This is the cause of your problems. You only need to open the file once in writing mode.
Morever, checking that the input stream is open will not tell you if the output stream is open too. Keep in mind that you open a file stream. If you want to check if it is properly open, you have to check it over the related object, not over another one.

How to disable cout output in the runtime?

I often use cout for debugging purpose in many different places in my code, and then I get frustrated and comment all of them manually.
Is there a way to suppress cout output in the runtime?
And more importantly, let's say I want to suppress all cout outputs, but I still want to see 1 specific output (let's say the final output of the program) in the terminal.
Is it possible to use an ""other way"" of printing to the terminal for showing the program output, and then when suppressing cout still see things that are printed using this ""other way""?
Sure, you can (example here):
int main() {
std::cout << "First message" << std::endl;
std::cout.setstate(std::ios_base::failbit);
std::cout << "Second message" << std::endl;
std::cout.clear();
std::cout << "Last message" << std::endl;
return 0;
}
Outputs:
First message
Last message
This is because putting the stream in fail state will make it silently discard any output, until the failbit is cleared.
To supress output, you can disconnect the underlying buffer from cout.
#include <iostream>
using namespace std;
int main(){
// get underlying buffer
streambuf* orig_buf = cout.rdbuf();
// set null
cout.rdbuf(NULL);
cout << "this will not be displayed." << endl;
// restore buffer
cout.rdbuf(orig_buf);
cout << "this will be dispalyed." << endl;
return 0;
}
Don't use cout for debugging purposes, but define a different object (or function, or macro) that calls through to it, then you can disable that function or macro in one single place.
You can user cerr - standard output stream for errors for your debug purposes.
Also, there is clog - standard output stream for logging.
Typically, they both behave like a cout.
Example:
cerr << 74 << endl;
Details: http://www.cplusplus.com/reference/iostream/cerr/
http://www.cplusplus.com/reference/iostream/clog/
If you include files which involve cout you may want to write the code at the start (outside of main), which can be done like this:
struct Clearer {
Clearer() { std::cout.setstate(std::ios::failbit); }
} output_clearer;
It seems you print debug messages. You could use TRACE within Visual C++/MFC or you just might want to create a Debug() function which takes care of it. You can implement it to turn on only if a distinct flag is set. A lot of programs use a command line parameter called verbose or -v for instance, to control the behavior of their log and debug messages.

std::cout won't print

Is there any circumstance when std::cout << "hello" doesn't work? I have a c/c++ code, however the std::cout doesn't print anything, not even constant strings (such as "hello").
Is there any way to check if cout is able/unable to open the stream? There are some member functions like good(), bad(), ... but I don't know which one is suitable for me.
Make sure you flush the stream. This is required because the output streams are buffered and you have no guarantee over when the buffer will be flushed unless you manually flush it yourself.
std::cout << "Hello" << std::endl;
std::endl will output a newline and flush the stream. Alternatively, std::flush will just do the flush. Flushing can also be done using the stream's member function:
std::cout.flush();
std::cout won't work on GUI apps!
Specific to MS Visual Studio:
When you want a console application and use MS Visual Studio, set project property "Linker -> System -> SubSystem" to Console. After creating a new Win32 project (for a native C++ app) in Visual Studio, this setting defaults to "Windows" which prevents std::cout from putting any output to the console.
To effectively disable buffering you can call this:
std::setvbuf(stdout, NULL, _IONBF, 0);
Alternatively, you can call your program and disable output buffering in the command line:
stdbuf -o 0 ./yourprogram --yourargs
Keep in mind this is not usually done for performance reasons.
It is probable that std::cout doesn't work due to buffering (what you're writing ends up in the buffer of std::cout instead of in the output).
You can do one of these things:
flush std::cout explicitly:
std::cout << "test" << std::flush; // std::flush is in <iostream>
std::cout << "test";
std::cout.flush(); // explicitly flush here
std::cout << "test" << std::endl; // endl sends newline char(s) and then flushes
use std::cerr instead. std::cerr is not buffered, but it uses a different stream (i.e. the second solution may not work for you if you're interested in more than "see message on console").

Capturing cout in Visual Studio 2005 output window?

I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?
I've finally implemented this, so I want to share it with you:
#include <vector>
#include <iostream>
#include <windows.h>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>
using namespace std;
namespace io = boost::iostreams;
struct DebugSink
{
typedef char char_type;
typedef io::sink_tag category;
std::vector<char> _vec;
std::streamsize write(const char *s, std::streamsize n)
{
_vec.assign(s, s+n);
_vec.push_back(0); // we must null-terminate for WINAPI
OutputDebugStringA(&_vec[0]);
return n;
}
};
int main()
{
typedef io::tee_device<DebugSink, std::streambuf> TeeDevice;
TeeDevice device(DebugSink(), *cout.rdbuf());
io::stream_buffer<TeeDevice> buf(device);
cout.rdbuf(&buf);
cout << "hello world!\n";
cout.flush(); // you may need to flush in some circumstances
}
BONUS TIP: If you write:
X:\full\file\name.txt(10) : message
to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the 'message' in status bar. It's very useful.
You can capture the output of cout like this, for example:
std::streambuf* old_rdbuf = std::cout.rdbuf();
std::stringbuf new_rdbuf;
// replace default output buffer with string buffer
std::cout.rdbuf(&new_rdbuf);
// write to new buffer, make sure to flush at the end
std::cout << "hello, world" << std::endl;
std::string s(new_rdbuf.str());
// restore the default buffer before destroying the new one
std::cout.rdbuf(old_rdbuf);
// show that the data actually went somewhere
std::cout << s.size() << ": " << s;
Magicking it into the Visual Studio 2005 output window is left as an exercise to a Visual Studio 2005 plugin developer. But you could probably redirect it elsewhere, like a file or a custom window, perhaps by writing a custom streambuf class (see also boost.iostream).
You can't do this.
If you want to output to the debugger's output window, call OutputDebugString.
I found this implementation of a 'teestream' which allows one output to go to multiple streams. You could implement a stream that sends data to OutputDebugString.
A combination of ben's answer and Mike Dimmick's: you would be implementing a stream_buf_ that ends up calling OutputDebugString. Maybe someone has done this already? Take a look at the two proposed Boost logging libraries.
Is this a case of the output screen just flashing and then dissapearing? if so you can keep it open by using cin as your last statement before return.
Also, depending on your intentions, and what libraries you are using, you may want to use the TRACE macro (MFC) or ATLTRACE (ATL).
Write to a std::ostringsteam and then TRACE that.
std::ostringstream oss;
oss << "w:=" << w << " u=" << u << " vt=" << vt << endl;
TRACE(oss.str().data());