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

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.

Related

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.

Getting the string(s) output from an exec command in C++

My problem is pretty simple, but I can't seem to find anything straightforward or specific to what I am trying to do. I'm simply using execl to list the files in the current folder that follow the same pattern (ie, execl("ls nameOfFile*.txt")). What I want to do now is grab those file names so that I can loop through and get the data out of them. Is there a simple way of doing this? Am I using the correct exec?
Thanks for any help or tips.
The signature of execl is
int execl(const char *path, const char *arg, ...);
You're supposed to pass the path to the executable as the first argument, and arguments for the executable as the subsequent arguments, so your calling syntax is wrong. Even if you fix that, it still won't do what you want. The only way execl and friends ever return control to the calling program is if an error occurs. This answer contains an excellent explanation of what execl does.
You were probably thinking of std::system, which you can pass an arbitrary string to, and have the OS execute that command. While that'll print the filenames to stdout, it's still not what you want, because system returns an error code resulting from executing the command line you specified, it has no way of capturing and returning whatever may be written to stdout by the command.
Unfortunately, there is nothing in the C++ standard library (yet) that allows you to list and iterate files from the filesystem. The preferred cross platform approach is to use Boost.Filesystem. Otherwise, there are platform specific APIs available, which are listed in this answer, along with a Boost usage example.

C++ reset locale to "C" globally?

In a project I am currently working on I link to a proprietary dynamic library. As soon as I run the library's initialize function, the behavior of logging and printing of numbers changes.
Commas have been inserted at every third decimal. i.e.
cout << 123456789 << endl
used to print out 123456789 and now it prints 123,456,789. This is horribly annoying, because this behavior is not what I want.
This issue is not only apparent in the binary I am compiling, but also shows up in all the couts and stringstreams in the libraries that I link to it.
I have tried using this line of code after calling the initialize function:
setlocale(LC_ALL,"C");
thinking it might reset my locale to the default but to no avail. The commas persist!
This snippet of code:
std::cout.imbue(std::locale("C"));
works to reset the locale of couts and every stringstream I apply it too. However, do I really need to call imbue on EVERY stringstream declared in EVERY library I link to? There are some libraries that are proprietary and I cannot actually change their source code.
There must be a way to reset the locale back to "C" globally?
I believe std::locale::global(std::locale("C")); should do the trick. See http://en.cppreference.com/w/cpp/locale/locale/global
Note that this only affects streams created after this call.
Any streams such as cout that the other library already imbued would have to be re-imbued back to the desired default locale.
And finally I would strongly suggest filing a defect report against the library you're using because it's pretty unjustifiable to to unilaterally make such striking global changes within your initialization function.

File created when using ofstream, but not ifstream and fstream/cannot seem to access gcount()

all. A new project of mine involves reading names from a file, and I realized, especially for somebody who likes to (attempt to, more like) makes games, reading/writing to store information is very useful. I looked into it and discovered the std library pulls through again. I subsequently realized that, at least for me, the libraries from ios, ios_base, iostream, fstream, etc etc, seem to be kind of complex.
I looked around, but am not quite sure why this specific approach does not work. It puzzles me because examples found online that seem to follow the library as they should - I will refer to one on cplusplus.com. Of interesting note is that one worked as expected, while another didn't. Far as I know, that is.
My problem is, I can create a file using ofstream, but not ifstream nor fstream. The way I understand it, there constructors, which I was using (which I beleive is identical paramaters as you would pass to open - that is, the filename and flags) are identical except in that they have different default perameters - ostream has ios::out, istream has ifstream has ios::in, and fstream has ios::in | ios::out - both flags, which is logical since it is the combination of both classes. Note this is not a problem of WHERE the file is created, rather, but the fact of its creation. I know this by two reasons. First, when using ofstream the file appears in expected directory, but not at all with ifstream nor fstream. Second, using the is_open function, (specifically, testing the expressions "while (is_open)" , the console never closed (I test most new concepts in the console because, well, it is simple), but with the others it did. If it had, then it never would have ended, since it can never go out of scope and thus the destructor spells the end for the open file.
My second problem was with using gcount - mostly how to access it. No matter how I tried (std::gcount, file::gcount, fstream::gcount...) it never recognized what it was. I was a bit befuddled.
Now comes a bit off off-topic ness to the specific issue, but more into the general reason of why I encountered this problem to begin with, which is sort of a discussion but I think it could be beneficial thing to learn, unless somehow I am the only one with this problem.
Firstly, the tuturial I had read over (learncpp.com) goes over the seekp/seekg functions, and said that it moves a relative amount in BYTES. It occured to me this is generally the same as a char, but is it possible that this is different on a different system (i.e, if a char was 2 bytes, you could figure this out, and apply this to the file searching), or will it always go by character, essentially, anyway?
And my main wonder... how to really use these tools to do things. Let's say I want to put a name on each line. I would be a bit unsure how to do that, - newline character perhaps? Or the other end, reading a name per line - how do you find the starting position of the next line? (my issue with gcount arrises because I figured you could use getline(), then gcount(), and voila, move that many characters... not sure if that works though)
Thanks.
To answer just one of your questions: you can't create a file with ifstream because, well, it doesn't create files; it's simply not intended to. This purpose of this class is to read data from existing files, and to open a file and read from it, it must exist first. Simple as that.
As far as fstream goes, you could make a case that it would make sense for it to create a file if none exists, but in fact, that's not what it does; the argument to fstream's constructor must be an existing file. If the named file doesn't exist, a failure bit is set in the object, and no file is created.

Why is the C++ syntax so complicated? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 13 years ago.
I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago.
This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?"
Writing "Hello world." in Python is as simple as "print 'Hello world.'" but in C++ it's:
# include <iostream>
using namespace std;
int main ()
{
cout << "Hello world.";
return 0;
}
I know there is probably a good reason for all of this but, why...
... do you have to include the <iostream> everytime? Do you ever not need it?
... same question for the standard library, when do you not need std::*?
... is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
... do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
... do you need to return 0 even when you are never going to use it?
This is probably because I'm learning such basic C++ but every program I've made so far looks like this, so I have to retype the same code over and over again. Isn't that redundant? Couldn't the compiler just input this code itself, since it's always the same (i.e. afaik you always include <iostream>, std, int main, return 0)
C++ is a more low-level language that executes without the context of an interpreter. As such, it has many different design choices than does Python, because C++ has no environment which it can rely on to manage information like types and memory. C++ can be used to write an operating system kernel where there is no code running on the machine except for the program itself, which means that the language (some library facilities are not available for so-called freestanding implementations) must be self-contained. This is why C++ has no equivalent to Python's eval, nor a means of determining members, etc. of a class, nor other features that require an execution environment (or a massive overhead in the program itself instead of such an environment)
For your individual questions:
do you have to include the <iostream> everytime? Do you ever not need it?
#include <iostream> is the directive that imports the <iostream> header into your program. <iostream> contains the standard input/output objects - in particular, cout. If you aren't using standard I/O objects (for instance, you use only file I/O, or your program uses a GUI library, or are writing an operating system kernel), you do not need <iostream>
same question for the standard library, when do you not need std::*?
std is the namespace containing all of the standard library. using namespace std; is sort of like from std import *, whereas a #include directive is (in this regard) more like a barebones import std statement. (in actual fact, the mechanism is rather different, because C++ does not use using namespace std; to automatically lookup objects in std; the using-directive only imports the names into the global namespace.)
I'll note here that using-directives (using namespace) are frequently frowned upon in C++ code, as they import a lot of names and can cause name clashes. using-declarations (using std::cout;) are preferred when possible, as is limiting the scope of a using-directive (for instance, to one function or to one source file). Don't ever put using namespace in a header without good reason.
is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
main is the entry point to the program - where execution starts. In Python, the __main__ module serves the same purpose. C++ does not execute code outside a defined function like Python does, so its entry point is a function rather than a module.
do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
std::cout is only needed if you don't import the cout name into the global namespace, either by a using-directive (using namespace std;) or by a using-declaration (using std::cout). In this regard, it is once again much like the distinction between Python's import std and from std import * or from std import cout.
The << is an overloaded operator for standard stream objects. cout << value calls cout's function to output value. Python needs no such extra code because print is built into the language; this does not make sense for C++, where there may not even be an operating system, much less an I/O library.
do you need to return 0 even when you are never going to use it?
No. main (and no other function) has an implicit return 0; at the end. The return value of main (or, if the exit function is called, the value passed to it) is passed back to the operating system as the exit code. 0 indicates the program successfully executed - that it encountered no errors, etc. If an error is encountered, a non-zero value should be returned (or passed to exit).
In response to your questions at the end of the post, it can be summed up with the philosophy of C++:
You don't pay for what you don't use.
You don't always need to use stdin or stdout (Windows/GUI apps?), nor will you always be using the STL, nor will everything you write necessarily use the standard main (winAPI) etc. As a previous poster said, C++ is lower level than Python. You will be exposed to more of the details, which offers you more control over what you're doing.
... do you have to include the
everytime? Do you ever not
need it?
You don't need it if you're not going to use iostreams in that module. In larger programs, few modules do any actual IO directly, and so few actually need to use iostreams.
Turning the question around: in python you need to import sys and/or os in most non-trivial programs. Why?
... same question for the standard
library, when do you not need std::*?
You can have the using line or you can use the std:: prefix. This is very similar to the choice python gives you of either saying "from sys import *" or "import sys" and then having to prefix things with "sys.". In python you have to say "sys.stdout". Is "std::cout" really any worse?
... is the "main" part a function? Do
you ever call the main function? Why
is it an integer? Why does C++ need to
have a main function but Python
doesn't?
Yes, main is a function. Typically you wouldn't call main yourself. The name "main" is reserved for the entry-point of your program. It returns an integer because the value returned is used as the status code of your program. In Python you can use sys.exit if you want to return a non-zero status code.
Python doesn't have the same convention because with Python you can have code in a module not in a function. This code is executed when you load the module. Interestingly, many people feel it is bad style to have code at the top-level of a module and will instead create a main function by doing something like this:
def main(argv):
# program goes here
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Also, in Python you tell the interpreter with module is the "main" module when you run it. eg: "python foo.py". In C, the "main" module is (effectively) the one with a function called main. (If there are multiple modules with a main function, it's a linker error.)
... do you need "std::cout << "? Isn't
that needlessly long and complicated
compared to Python?
The equivalent in Python is actually "sys.stdout.write(...)". Python's print statement is a special-case short-hand.
That said, many people do feel the iostreams convention of using bit-shifting operators for IO was a bad idea. Ironically, Python seems to have been "inspired" by this syntax. If you want to use print to write to somewhere other than stdout you can say:
print >>file, "Hello"
... do you need to return 0 even when
you are never going to use it?
You aren't going to use it, but your program will. As mentioned earlier, the value you return is the status code of your program.
Aside: I actually do feel that C++ is overcomplicated, but not because of any of the points you mention. All of the differences you mention go away (in the sense that you need just as much complexity in Python) once you start writing non-trivial programs that have multiple modules and do more than just writing to stdout.
You include <iostream> when you want to output things to the console. Since printing "Hello world" involves console output, you need iostream.
The main function is called by the operating system, basically. It gets called with the command-line arguments passed to the program. It returns an integer because the program must return an error code to the operating system (this is the standard way for determining if the last command was successful).
You can always use printf("hello world"); instead of std::cout << "hello world"; if you want to go C style. It's a bit quicker to write and lets you do formatted output.
You return 0 from main to indicate that the program executed successfully.
The compiler does not automatically include all the standard libraries and use namespace std because sometimes name collisions can result between your code and library code that you may not actually need at all. You don't always need all the libraries. Likewise, sometimes you are using a different main routine (Windows development comes to mind with its own, different WinMain starting function). The compiler also does not automatically return 0 because sometimes the program needs to indicate that it completed unsuccessfully.
There are good reasons for all these things. C++ is a very broad language it is used for everything from small embedded systems to giant applications built by 100s of programmers. The use case of a guy building a small program to run on a desktop is by no means the only one. So sometimes you are building library components. In that case no main(). Sometimes you are working on a tiny system with no standard library. In that case no std. Sometimes you want to build a Unix tool that works with other Unix text tools and signals its completion status with an int returned from main().
In other words the things you complain about are boilerplate to you. But they are vital details that vary to other users of the language.
This reminds me of The Evolution of a Programmer. Some of the languages and technologies demonstrated are a bit dated now, but you should get the general idea. :)
One of the reasons C++ is rather complicated is because it was designed to address problems that crop up in large programs. At the time C++ was created as AT&T, their biggest C program was about 10 million lines of code. At that scale, C doesn't function very well. C++ addresses many of the problems you get with that kind of program.
With that said, it's also possible to answer the original questions:
You would include <iostream> where it's needed. If you've got 10.000 C++ files, it's quite common that less than 1000, sometimes less than 100 will produce user-visible output.
A statement like print "Hello, world" assumes that there is a default output, but makes it hard to generalize. The cout << "Hello, world" form makes it explicit where the output goes, but the same form also allows cerr << "Goodbye, world" and MyTmpFile << "Starting phase #" << i
The standard library is in the std:: namespace. My 10.000 files will be in an additional 25 namespaces.
main is an oddity in many ways, being the startup function.
Baldur:
You don't always need <iostream>. The only things that you will always need are:
A main function (or a WinMain, if you're writing Win32 apps).
Variables, functions, operators, language constructs (if, while, etc.).
The ability to include functionality from libraries into your program.
Everything else is application-specific.
As other posters say, the return value of the main function is an error code1. If main returns 0, be happy: everything worked OK!
1This is useful when you write programs that "communicate" with other programs. The most simple way that a program can "tell" another whether it executed properly is using an error code.
As people have said, the simple answer is that they're different languages, with different goals. To answer your specific questions...
... do you have to include the <iostream> everytime? Do you ever not need it?
<iostream> is one of the header files for iostreams, the part of the C++ standard library responsible for input/output; in this instance, you need it to gain access to std::cout. If you're not doing I/O operations in a source file, you don't need to include it -- for example, most files containing class definitions probably won't need <iostream>.
... same question for the standard library, when do you not need std::*?
std is the name of namespace containing classes in the standard library; it's there to avoid name collisions. Python has packages and modules to do this.
You can use the using statement to bring items from another namespace into your current scope, see this FAQ entry for an example (and an explanation of why it's bad to blindly bring all of std into scope!).
... why is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
Executable statements in C++ have to be contained within a function, and the main function is defined as where execution begins. In Python, executable statements can be placed at the top-level of a file, and execution is defined to .
You can call main() if you wish -- it's just a function, after all -- but there's not often a reason to do this. Behind the scenes, most implementations of C++ call main() for you once some startup housekeeping has been done by the runtime library.
The return value of main() is returned back to the operating system. This stems from C and UNIX, in which application programs are required to provide a 1-byte exit status code, and returning that value from main() is a clear way of expressing this.
... why do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
This is just a design difference. iostreams is a fairly complex beast with lots of features, and one of the side-effects of this is that the syntax is a bit ugly for simple tasks at times.
... why do you need to return 0 even when you are never going to use it?
You do use it; this is the value returned to the operating system as the exit status of the program.
Python is high-level language. C++ is middle-level language.