I try to improve my code to become a better code with the book "C++ Das umfassende Handbuch" by Torsten T.Will. He writes that instead of using cout, it is better to use ostream as this includes also cerr (so error print out).
The example he uses is:
1 2 3
...
void drucke (std::ostream& os) {
os << "Hello";
My current code is a password programming on a very simple basis. The start is:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <Account.h>
#include <cstring>
using std::cout; using std::cin;
void Init_()
{
string question;
cout << "Do you want to 'login', set a new 'password' or a complete new 'account'" <<endl;
getline(cin,question);
cout << endl;
This works. According to his example I started to change the code to:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <Account.h>
#include <cstring>
using std::ostream; using std::cin;
void Init_(std::ostream& os)
{
string question;
os << "Do you want to 'login', set a new 'password' or a complete new 'account'" <<endl;
getline(cin,question);
cout << endl;
I use Code::Blocks 17.12 with console application. But here ostream is not even recognized which means the type "ostream" in the using declaration is black.
Therefore I tried to replace the type "ostream" with "iostream". "iostream" is in green letters, but still I get failure messages that this does not work.
It just states "error: within this content". But it opens a new page "istream" with a failure in line 859 "basic_iostream()" which states "error: 'std::basic_iostream<_CharT, _Traits>::basic_iostream() [with _CharT = char; _T..."
I would appreciate some help.
@Hay9
The problem is that you are confusing a type (or class) of thing with a concrete example of that thing. That is:
std::ostream is an abstract base class.
std::cout is a global object that you can use.
To create your own ostreams, you must create them, as with any other variable. For example, here is a program to print output to either a named file (given as command-line argument) or to standard output:
#include <fstream>
#include <iostream>
void print( std::ostream& os ) // os is any ostream given as argument to the function
{
os << "Hello world!\n";
os << 42 << "\n";
}
int main( int argc, char** argv )
{
if (argc == 2)
{
std::string filename = argv[1]; // The filename given as command-line argument
std::ofstream f( filename ); // Create the output file stream
print( f ); // Write information to the file
}
else
{
print( std::cout ); // Write information to standard output
}
}
I understand now that ostream& is a function class and I need to create an object for it to work. Your example also shows in a nice way that I need this if I want to overload the print function.
So I do not need it at my first question in my password code, but I can use it later to write a valid password to a file and an invalid password to the screen with an error statement (incl. the try throw and catch).