Printing to printer

I have written in C language quite a bit but I'm new to C++/Visual C++.
Trying to write to the default printer from a Windows 10 box. I'm told that the following code segment will do that. It is being compiled as a C++ console app in Visual Studio 2015.

Here is the code:

******************************************************************************
// ConsoleApplication5.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <fstream>
#include "stdafx.h"

using namespace std;

int main()
{
ofstream printer("LPT1");
if (!printer)
{
return 1;
}

printer << "Test Test Test\n";
printer << "\f";
printer.close();
return 0;
}

*******************************************************************************

When VS2015 builds it...it gives up several errors. The first of which is
C2065: ofstream undeclared identifier. I thought ofstream was defined in ifstream or fstream.

Can someone provide some guidance here. Thanks!

Jim


The code you provided compiles fine on my machine. Perhaps the code you provided isn't the code you actually tried to compile?

OK...I placed the #include "stdafx.h" first in the include list and it now compiles fine.
Apparently this is a Microsoft specific rule. The problem now is that it runs in a window but NOTHING happens at the printer. I checked the print que and it is empty.

Jim
Well printing to "LPT1" is really a DOS hangover that is probably not going to work. First if your printer is not connected to a parallel port there is no way printing to "LPT1" will work, because "LPT1" is the first parallel port. Second if you have a modern Windows printer, you can't print directly to the printer, you need to go through a driver. You'll need to investigate the Windows printing system documentation and use Windows API calls to properly access the printer.

Sorry but your program in no way interacts with an actual, physical printer or printer driver.
You have only made an ofstream object, which creates a file called "LPT1", and puts some text into it.
(Edit: Sorry, I guess LPT1 is a special, see jlb's answer. Still probably won't work though)

To actually work with a printer, you're gonna probably need platform-specific code. Probably a bit complicated.
Try searching google and MSDN, I'm not an expert in that stuff.
https://msdn.microsoft.com/en-us/library/windows/desktop/ff686805(v=vs.85).aspx

Here's for example, some code that apparently prints the screen to a printer https://support.microsoft.com/en-us/kb/186736
Last edited on
Well...I guess the short answer is "you can't get there from here". So I will start cramming my brain with the wonderful world of Win API programming. (Wonderful!)

Jim
Topic archived. No new replies allowed.