Capturing cout in Visual Studio 2005 output window? - c++

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());

Related

How to enter to and read from a console program?

For a program that I want to write, I have to enter commands to and read from a console program, and I have no idea how to.
For understanding, perhaps a solution to the following example would be helpful:
I want to write a program that squares all natural numbers up to 100 and saves the result to a text file. Assume that I don't know how to square numbers and therefore use the executable file square_x.exe with the following (unavailable) source code:
#include <iostream>
using namespace std;
int main(){
double in;
cout << "Input: ";
while(cin>>in){
cout << in << static_cast<char>(253)/*²*/ << " = " << in*in << endl
<< endl
<< "Input: ";
}
return 0;
}
How then must I add to the following code fragment? (Proposedly, where indicated by "Somehow"):
#include <fstream>
using namespace std;
ofstream file;
void writeToFile( const char* name, const char* content ){
file.open( name, ios::app );
file << content;
file.close();
}
int main(){
char buffer[30], buffer2[50];
//Somehow call square_x.exe
for( int i = 1 ; i <= 100 ; i++ ){
//Somehow send i to square_x.exe
//Somehow get a result from square_x.exe and safe it to buffer2
//Extract from the got string the result of the calculation
strtok(buffer2," "); strtok(0, " ");
strncpy(buffer2,strtok(0, " \n"),sizeof(buffer2)-1);
sprintf( buffer , "%d\n%s\n\n" , i , buffer2 );
writeToFile( "list.txt", buffer );
}
//Somehow close square_x.exe
return 0;
}
I asked a friend of mine if he could help me with that and he sent me this. But since I have no idea how I would have to change this code to fulfill my needs, he then sent me here.
I assume that want you really want is the way to pass input to an auxilliary program and get its output.
The referenced link explains how to do it using WinAPI functions. Unfortunately, there is no simpler solution on Windows, because of the lacking of a fork function(*).
Taking the link as reference you must replace in your source //Somehow call square_x.exe with pipes and child process creation (CreatePipeand CreateProcess API calls, child process here is square_x.exe). Then to send something to the child, you just use WriteFile on the write end of the input pipe, and to read from the child, you use ReadFile from the read end of the output pipe.
But you example will be a little harder, because you child adds the noisy string "Input: " that you will have to ignore.
Try to put this in your code, and come back here to ask another question (with the new code) if you are stuck.
(*) But you could find a library that deals with all that gory details for you, such as libexecstream proposed by #a486408.
You can try using libexecstream - it allows you to launch new processes and communicate with them using c++ iostreams without digging into OS-specific stuff.

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.

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

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");

sstream not working...(STILL)

I am trying to get a double to be a string through stringstream, but it is not working.
std::string MatlabPlotter::getTimeVector( unsigned int xvector_size, double ts ){
std::string tv;
ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
It outputs only "0:" on my console...
I'm working on two projects, both with the same problem. I'm posting a different one, which runs into the same problem. It is posted here:
http://pastebin.com/m2dd76a63
I have three classes PolyClass.h and .cpp, and the main. The function with the problem is PrintPoly. Can someone help me out? Thanks a bunch!!
You're printing correctly, however your logic in the order of printing is incorrect.
I modified it to work they way I think you wanted it to, let me know if this helps.
http://pastebin.com/d3e6e8263
Old answer:
Your code works, though ostringstream is in the std namespace. The problem is in your file printing code.
Can I see your call to the function?
I made a test case:
// #include necessary headers
int main(void)
{
std::string s;
s = MatlabPlotter::getTimeVector(1,1.0);
}
The output I get is 0:1:1
The following code is 100% correct:
#include <iostream>
#include <sstream>
#include <string>
// removed MatlabPlotter namespace, should have no effect
std::string getTimeVector(unsigned int xvector_size, double ts)
{
// std::string tv; // not needed
std::ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
int main(void)
{
// all work
// 1:
getTimeVector(0, 3.1415);
// 2: (note, prints twice, once in the function, once outside)
std::cout << getTimeVector(0, 3.1415) << std::endl;
// 3: (note, prints twice, once in the function, once outside)
std::string r = getTimeVector(0, 3.1415);
std::cout << r << std::endl;
}
Find where we differ, that's likely your source of error. Because it stops at your double, I'm guessing the double you're trying to print is infinity, NaN (not a number), or some other error state.
I can't really help with the "no output" part of this, as you didn't show your code that tries to output this. As a guess, did you perhaps not put an EOL in there somehow? Some systems won't give any text output until they hit a newline. You can do this by tacking a << std::endl onto your line, or a '\n' to your string.
Since you didn't put down a using for it, you need to use the type std::ostringstream. This is similar to how you had to use "std:string" instead of just "string".
Also, were it me, I'd get rid of that temp variable and just return ss.str(); It is less code (to possibly get wrong), and probabaly less work for the program.
Well, I tried the code you linked to and it outputs
B 4
A 5
B 4
C 3
x^ + 5x^ + 3
for me before crashing although the crash happens after PrintPoly. From looking at the code this is what I'd expect it to print. Are you saying you get no integers appearing after the letters?
Thanks all for your input! Not sure of the exact error, but it must be some setting in XCode which is messing it up. I made a CMakeLists.txt file and compiled it from the terminal using
cmake -G XCode ..
and produced an XCode project. I ran it, and now it works fine...now would anyone happen to know what might cause XCode to do this? I'm running version 3.2 with the following:
64-bit
Component versions
Xcode IDE: 1610.0
Xcode Core: 1608.0
ToolSupport: 1591.0

Is there a decent wait function in C++?

One of the first things I learned in C++ was that
#include <iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
would simply appear and disappear extremely quickly without pause. To prevent this, I had to go to notepad, and save
helloworld.exe
pause
ase
helloworld.bat
This got tedious when I needed to create a bunch of small test programs, and eventually I simply put while(true); at the end on most of my test programs, just so I could see the results. Is there a better wait function I can use?
you can require the user to hit enter before closing the program... something like this works.
#include <iostream>
int main()
{
std::cout << "Hello, World\n";
std::cin.ignore();
return 0;
}
The cin reads in user input, and the .ignore() function of cin tells the program to just ignore the input. The program will continue once the user hits enter.
Link
Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
For forcing your programme stop or wait, you have several options :
sleep(unsigned int)
The value has to be a positive integer in millisecond.
That means that if you want your programme wait for 2 seconds, enter 2000.
Here's an example :
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 seconds
cout << "test" << endl;
sleep(2000); // wait for 2 seconds before closing
return 0;
}
If you wait too long, that probably means the parameter is in seconds. So change it to this:
sleep(5);
For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting problems, try to add of one this library on the beginning of the code.
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
system("PAUSE")
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
If you get the message "error: 'system' was not declared in this scope" just add
the following line at the biggining of the code :
#include <cstdlib>
cin.ignore()
The same result can be reached by using cin.ignore() :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
cin.get()
example :
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
getch()
Just don't forget to add the library conio.h :
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
You can have message telling you to use _getch() insted of getch
Lots of people have suggested POSIX sleep, Windows Sleep, Windows system("pause"), C++ cin.get()… there's even a DOS getch() in there, from roughly the late 1920s.
Please don't do any of these.
None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)
Keeping the console window open so you can read the output of your program is not the responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.
Instead, you should configure your environment to keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach! I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.
An interim, quick-start approach would be to change your IDE's run command from cmd.exe <myprogram> or <myprogram>, to cmd.exe /K <myprogram>. The /K switch to cmd.exe makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.
I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.
The appearance and disappearance of a window for displaying text is a feature of how you are running the program, not of C++.
Run in a persistent command line environment, or include windowing support in your program, or use sleep or wait on input as shown in other answers.
the equivalent to the batch program would be
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
std::cin.get();
return 0;
}
The additional line does exactly what PAUSE does, waits for a single character input
There is a C++11 way of doing it. It is quite simple, and I believe it is portable. Of course, as Lightness Races in Orbit pointed out, you should not do this in order to be able to see an Hello World in your terminal, but there exist some good reason to use a wait function. Without further ado,
#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
std::this_thread::sleep_for(std::chrono::microseconds{});
More details are available here. See also sleep_until.
Actually, contrary to the other answers, I believe that OP's solution is the one that is most elegant.
Here's what you gain by using an external .bat wrapper:
The application obviously waits for user input, so it already does what you want.
You don't clutter the code with awkward calls. Who should wait? main()?
You don't need to deal with cross platform issues - see how many people suggested system("pause") here.
Without this, to test your executable in automatic way in black box testing model, you need to simulate the enter keypress (unless you do things mentioned in the footnote).
Perhaps most importantly - should any user want to run your application through terminal (cmd.exe on Windows platform), they don't want to wait, since they'll see the output anyway. With the .bat wrapper technique, they can decide whether to run the .bat (or .sh) wrapper, or run the executable directly.
Focusing on the last two points - with any other technique, I'd expect the program to offer at least --no-wait switch so that I, as the user, can use the application with all sort of operations such as piping the output, chaining it with other programs etc. These are part of normal CLI workflow, and adding waiting at the end when you're already inside a terminal just gets in the way and destroys user experience.
For these reasons, IMO .bat solution is the nicest here.
What you have can be written easier.
Instead of:
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
write
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
system("PAUSE");
return 0;
}
The system function executes anything you give it as if it was written in the command prompt. It suspends execution of your program while the command is executing so you can do anything with it, you can even compile programs from your cpp program.
Syntax:
void sleep(unsigned seconds);
sleep() suspends execution for an interval (seconds).
With a call to sleep, the current program is suspended from execution for the number of seconds specified by the argument seconds. The interval is accurate only to the nearest hundredth of a second or to the accuracy of the operating system clock, whichever is less accurate.
This example should make it clear:
#include <dos.h>
#include <stdio.h>
#include <conio.h>
int main()
{
printf("Message 1\n");
sleep(2); //Parameter in sleep is in seconds
printf("Message 2 a two seconds after Message 1");
return 0;
}
Remember you have to #include dos.h
EDIT:
You could also use winAPI.
VOID WINAPI Sleep(
DWORD dwMilliseconds
);
Sleep Function(Windows)
Just a note,the parameter in the function provided by winapi is in milliseconds ,so the sleep line at the code snippet above would look like this "Sleep(2000);"
getchar() provides a simplistic answer (waits for keyboard input).
Call Sleep(milliseconds) to sleep before exit.
Sleep function (MSDN)
You can use sleep() or usleep().
// Wait 5 seconds
sleep( 5 );
Well, this is an old post but I will just contribute to the question -- someone may find it useful later:
adding 'cin.get();' function just before the return of the main() seems to always stop the program from exiting before printing the results: see sample code below:
int main(){
string fname, lname;
//ask user to enter name first and last name
cout << "Please enter your first name: ";
cin >> fname;
cout << "Please enter your last name: ";
cin >> lname;
cout << "\n\n\n\nyour first name is: " << fname << "\nyour last name is: "
<< lname <<endl;
//stop program from exiting before printing results on the screen
cin.get();
return 0;
}
Before the return statement in you main, insert this code:
system("pause");
This will hold the console until you hit a key.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause");
return 0; // this return statement isn't necessary
}
The second thing to learn (one would argue that this should be the first) is the command line interface of your OS and compiler/linker flags and switches.