Eclipse Luna C++ endl - c++

I just started learning C++ and I noticed that when I do cout << "Some text" << endl; endl is not bold. I want to make sure that this is not a problem and it won't cause any future problems.

Do not (<---- this intentionally bold!) use std::endl! Ever. It has no place in C++. It was a good idea but it is being abused. If you want a newline, use '\n'. If you want a flush, use a std::flush. Here is a more thorough explanation.
I don't know about Eclipse but I'd assume that it highlight keywords in bold: std::endl isn't a keyword. It is just a function (well, actually it is a function template but the details really don't matter) with a specific signature (std::ostream&(std::ostream&)) pointers to which are treated special when using it with an output operator on a std::ostream: the operator will just call the function with the stream as argument. These functions are called manipulators.

Related

Question std::cout in C++ how exactly does the stream work?

Say we have:
std::cout << "Something";
How exactly is this working? I just want to make sure I understand this well and, from what I've been reading, is it okay to say that basically the insertion operator inserts the string literal "Something" into the standard output stream?
But what happens after that? Where does the standard output stream lead? Can anyone explain this?
That's basically the only part I don't get: I have the string literal "Something" in the standard output stream, but where does the stream lead?
The technical details vary between the different Operating Systems, but the basics are the same:
Every program has usually 3 standard streams: out (cout), in (cin), and err (cerr) (same as out, but used for errors). Those streams are nothing on their own; they exist to be used by a third party. That third party may be, for example, the terminal. When you execute a program form the terminal, it attaches to the program streams and show their output/request their input in the terminal.
If you wanted to do the same, you could execute a command yourself from your program, and take the out/in/err streams to read or write from/to them.
You have an example of that here: How do I execute a command and get the output of the command within C++ using POSIX?
Edit: When talking about C++, remember that cout << "anything" is just syntactic sugar for the function cout.operator<<("anything"). And that function "simply" writes to the stream
so,'std' is the namespace in which is stored everything found in the standard library , so basically you are saying "hey C++, go to 'std' storage and find cout command and run it" at least I know 'std' is this. and when you are saying using namespace std; you tell the compiler "take everything that's in the std namespace and dump it in the global namespace".
I hope it helped you to understand.

Using std::cout on STM32 microcontroller

I managed to use printf() on my STM32 (CortexM7) compiling under C++, by defining functions like _write and _read and so on.
But I wanted to use std::cout instead of printf. However including <iostream> yields like 300 errors.
Do you know what has to be done to use cout with custom char printing functions?
Compiler used G++ 6.2.
I have found partial solution. You can make class (even name it cout) and overload operator << for different types and inside execute printf() with proper format string. Maybe not most efficient but for UART is ok.
So I don't need answer anymore, but if someone knows, then for curiosity you can post it.

What exactly are cout/cin?

I know Java and now want to learn C++. I can't understand what are cout (character output stream) and cin (character input). Are these global variables? Then why
"My message">>cout;
doesn't work? But
cout<<"My message";
works.
cout is an instance of the class std::ostream, and yes, it's a global variable. But operator>>(char *, ostream& os); hasn't been declared by the relevant header, so "My message">>cout; will give an error of something like "can't find an operator >> which takes arguments const char * and std::ostream" (and possibly a lot more errors because sometimes compilers get very confused by these sort of things).
cin is the same thing, except std::istream
If you really want to mess with peoples heads, you could do:
template<typename T>
std::ostream& operator>>(T x, std::ostream& os)
{
os << x;
return os;
}
Of course, it won't work for "My Message " >> "Some other string" >> cout;, which is probably one of the reasons it's not done that way.
Note that this is simply slight abuse of the operator overloading, where we have a custom type as the left-hand side, and standard or non-standard type on the right hand side. cout is no different from some other variable of a custom type.
std::cout and std::cin are indeed global variables. Your code doesn't compile because that's not the way the language works. You have to put the stream on the left, and then the operator and then the variables you are streaming into/out of. (For output, you can use literals and expressions as well as variables.)
consider the arrows as streams. << stands for output stream , while >> stands for input stream.
so cout << "hello" means output to screen
when cin >> a means asks from a user input for variable a
cout can also use "+" like for example you can add more strings to one stream like this
cout << "Hello" << "world" << "I am john";
cin in the same way can ask for input from multiple variables
cin >> a >> b ; will ask from user to input two times one for each variable
iostream is a header file which contain classes handling input and output operations for a console. Its like you create a object when you say "cin" for the input class handling input operation for a console in the header file. Same can be said about "cout" where a object is being created from a class handling output operation to a console in the header file.
When you consider "cin", imagine creating a pipe connected to the console and your program and an object "cin" taking your inputs from the console which you provide through your keyboard and dumping them on to the program. That's the reason you can see having a ">>" operator for cin and you can find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cin".
Whereas for "cout", imagine creating a pipe connected to the console and your program and an object "cout" taking its input from the program and dumping them on to the console. That's the reason you can see having a "<<" operator for cout and you find the analogy to the pipe where the operator is taking the job of specifying the direction for the object "cout".
So basically you need to first specify what object you would be creating for your operations and then assigning an operator to accomplish your task. If you include the header file, then its like you could use those objects anywhere throughout your program.
So, "My message">>cout; doesn't function the way you expect it to be because there is no object and an operator to accomplish your task whereas cout<<"My message"; does.
The technical aspects have been described by Mats Petersson. This is just to give you a general picture of what's actually happening pictorially. Hope this helps you.

Convert from C++ style printing to my_printf()

C++ purists may want to look away now. You will hate this.
I have been given an open source windows console app that I am merging with a pre-existing, very old, very large windows app of my own. My old program started life as pure C though recently has been tweaked so that it can compile as C++. My program makes extensive use of a my_printf() function which prints text to a window.
The old console app does its printing C++ style via streams (I have never used this type of printing mechanism before).
When converting the console app to work under my system I could manually edit all the lines that do printing so that they use my_printf() instead. But before I embarked on that I thought I'd just check with StackOverflow to see if I was missing a trick. For example I could imagine somehow letting the C++ prints be done via the stream and then somehow scooping the final text somewhere and then calling my_printf() with the result. Might that be possible?
EDIT: please note my knowledge of C++ is extremely limited and I may need to look some things up in order to understand your answers so please use language that facilitates this.
There's indeed a trivial trick. But C++ impurists will hate the fact that C++ has a pure solution ;)
std::ostream is responsible for formatting, but not printing itself. That's handled by std::streambuf. std::cout combines a std::ostream formatter with a std::streambuf-derived object that writes to stdout.
However, you can change the streambuf backing an ostream with ostream::rdbuf(newbuf). As std::cout is just another ostream, you can replace its streambuf too. In this case, you only need to come up with a streambuf-derived class that writes already-formatted output to my_printf(). That should be quite trivial.
You might find string streams useful. For example:
std::ostringstream os;
os << "Print " << whatever << data;
my_printf( "%s", os.str().c_str() );
In case you were feeling adventurous, you could write your own streambuf instead that used my_printf underneath, and inject it into the stream object that is currently used in output statements (e.g. std::cout). Be warned that this latter approach might not be trivial, however it would result in almost no changes to existing codebase.
Subclass std::ostream and make operator << call my_print_f(). You can use internal stringstream in your stream to retrieve string representation of operator << arguments.
Then you'd just have to do find&replace, replacing cout (or whatever stream you directed your output to in the console app) with an instance of your stream class.
Something along these lines might be helpful:
http://www.codeproject.com/KB/debug/debugout.aspx
Should be obvious where the meat of it is, so you can make it print via your own systems, or what have you. In theory, you'd need only search for references to std::cout and replace them with references to your own object.
Overloading the global operator<< is probably what will solve your problem:
#include <iostream>
#include <cstdio>
static int
my_printf (const char* s)
{
printf ("my_printf: %s\n", s);
}
namespace std {
std::ostream& operator<< (std::ostream& out, const char* s)
{
my_printf (s);
return out;
}
}
int
main ()
{
std::cout << "hello, world"; // => my_printf: hello, world
return 0;
}

C++ pipes in Objective-C

I made the transition from C++ to objective-C a while ago, and am now finding NSLog() tiresome. Instead, still in Objective-C, I would like to be able to write something like
stdout << "The answer is " << 42 << "\n";
(I know that NSLog prints to stderr, I could put up with writing stderr << "Hello world";)
Basically, I just want to be able to use the C++ pipe syntax in Objective-C.
I don't care about speed (within reason) or if the only method uses precompiler macros or other hack-ish things.
You really should get used to format strings as in NSLog. The C++ style syntax may be easy to write, but it is a nightmare to maintain. Think about internationalization. A format string can easily be loaded at runtime. Cocoa provides the function NSLocalizedString for that. But for C++’s stream operators you probably have to write different code for every language.
What you're wanting is stream operations.
There isn't a really 'good' way to do this in Cocoa, I have a library that I never really fleshed out that would allow you to do something 'near' this, but still wouldn't get a lot of the benifits.
http://github.com/jweinberg/Objective-Curry/blob/master/OCFileStream.m
Starting from there you would be able to write a class that did
[[[stdOutStream write:#"10"] write:[bleh description]] write:#"more stuff"];