C++ I/O library - c++

I tried googling this but I get different answers at different places. I want to know the cases wherein one should use one of the following:
#include <stdio>
#include <cstdio>
#include <iostream>
I cannot figure out the difference since in my case all my C++ programs seem to work if I use these interchangeably. That being said, iostream seems to support the stream of input and output by defining cin and cout etc. However, I maybe wrong. I would appreciate answers / credible citations for the usage of these with reference to the C++ standards. I wonder if there are any performance benefits involved in using one over the other.

Nonstandard Headers
<stdio> is not defined in any of the standards that I know of.
Standardized Headers for C
<stdio.h> is the c header containing functions like printf() and scanf().
Standardized Headers for C++
<stdio.h> is included in the c++ standard but is deprecated.
<cstdio> is the c++ header that includes things like printf() and scanf().
<iostream> is a c++ header that include things like std::cout, std::cerr and std::cin.

stdio is for standard IO in C. It should have a .h at the end. In C++, all C headers have been encapsulated in cxxxxxx headers (without .h). So, <stdio.h> is the same as <cstudio>. These offer functions, like printf and scanf, for simple IO.
iostream on the other hand is an IO library for C++, and offers streams like cin and cout, as you mentioned.
Depending on your application you can use them interchangeably for most of the time. The syntax is going to be different, obviously.
Formatting text can be easier using the C functions. For example:
printf("item %04d has a value of %+.6e\n", index, value);
is easier to write than (needs <iomanip> in addition to <iostream>):
std::cout << "item " << std::setw(4) << std::setfill('0') << index
<< "has a value of " << std::setprecision(6) << value << "\n";
However, you need to be more careful when using the first one. For example, the following line won't produce a compile error (but as sharth mentioned, you might get warnings when compiling) but will cause runtime issues:
printf("I wonder what will happen? %d\n");
I don't think there is a lot of difference in their performance as most of the stream "magic" happens in compile time, and they should produce similar results. I'm not 100% sure though, so correct me if I'm wrong.

there is no stdio (stdio.h and cstdio). the 'c' and the missing '.h' in the header name indicates that it's the C++ version of the C header.
check cstdio and iostream (references)
some compilers (including MSVC) include stl headers in other stl headers which leads to the effect you observed. this is not portable though!
if you are concerned with performance: use the C++ variants and check this

Related

Is string header file needed anymore? [duplicate]

This question already has answers here:
C++ code compiles without include
(2 answers)
Why does omission of "#include <string>" only sometimes cause compilation failures?
(7 answers)
Closed 3 years ago.
So I am learning C++ at the moment, and at some point I saw that you "have to" #include <string> at the top of your code to use strings.But when I run my code, it does the same thing in both cases.So is it really needed to use it?
#include <iostream>
using namespace std;
int main()
{
string fullName;
cout << "Type your full name: ";
getline(cin, fullName);
cout << "Your name is: " << fullName;
}
Some compiler implementations include the header <string> in the header <iostream>.
But you shall not rely on this.
A compiler is not required to accept your program if you don't.
It might (coincidentally) be included through a different header and work anyway, but that might not be the case after your next compiler update or if you move to different platform.
Whether you "have to" include it is mostly down to how strict an environment you're working in – if you're hacking away at home you can do whatever, but if you're working for somebody else you're usually expected to Do The Right Thing.
Don't rely on transitive includes. Your implementation may include whatever it wants in other headers that may cause your code to work, but you cannot rely on that. A good, portable, robust program includes what it needs, when it needs it, explicitly. That way it stays working when you change compiler, standard library, Operating System, etc.
In C++, #include just says to paste the code from the file included into that location. If something is already #includeing string, then the compiler won't care if anything after it includes it.
This does not mean you should do that! Always include what you need. Don't rely on other headers, especially those from libraries, including anything for you.

Why does a header file work in Windows but not on Mac & Linux? (strrev)

I am exploring the work on cstring inside a C++ code. One of the functions that is commonly used is strrev().
But I found that this function is considered undefined on Mac & Linux, even if I included the header file <cstring> or <string.h>.
However, the function works fine on Windows.
(I am aware that I can define the function myself as the solution presented in here strrev not available on Linux)
This might be a very naive question, but aren't the definitions of header files supposed to be the same across different platforms? or does each platform have a different definition of the header file?
Another weird thing that is I did not find strrev() in the description of the <cstring> header file (cstring header file description), but if I don't include this header file on Windows I get an error and the error is resolved when I include it.
One of the functions that is commonly used is strrev().
Actually, other than in programming classwork, I can't think of any viable reason why strrev() would be useful. I don't think I've had a need for such a beast in my entire multi-decade career :-)
The reason it's not defined in some platforms is because it's not mandated by the C++ standard.
The reason why it's defined in some other implementations is because the standard dictates what must to be made available, not what mustn't. In other words, implementations are allowed to include it, they're just not required to include it.
An implementation can choose to include all sorts of wonderful extra stuff, provided it doesn't break any of the stuff mandated by the standard.
It's an implementation specific decision to include certain functions other than the standard ones.
However, in C++, you may use std::reverse from <algorithm> header to reverse the string.
Here's an example:
#include <iostream>
#include <algorithm>
int main()
{
char s[] = "Hello World!";
std::reverse( std::begin(s), std::end(s) );
for ( const auto& i : s )
{
std::cout << i;
}
return 0;
}
Output string:
!dlroW olleH
here is a link where you shall find the list of function & class that should be in the header according to the standard : http://www.cplusplus.com/reference/
About the question on the header itself, C++ standard does not propose one uniformed header, but the list of what is required.
And the definitions in the headers will even vary for the same compiler, from one target to another (32 or 64 bits, etc.. ). If you check the iostream header for GCC, for instance, it includes 3 files :
#include <bits/c++config.h>
#include <ostream>
#include <istream>
the header under the bits/ directory usually vary from one target to another, and you don't directly include it in your own application.

Using Linux API headers made for C in C++

Let's consider this piece of code:
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
using namespace std;
int main(void) {
char hi[14] = "Hello world!\n";
if (write(1, hi, strlen(hi)) < 0) {
perror("write");
}
cout << "Done" << endl;
return 0;
}
Here, I'm mixing all kinds of C and C++ code to make something ... work. I'm writing on stdout directly and using some C headers like string.h and stdio.h. Is this considered bad? Could undefined behavior arise? Is C code "compatible" with C++ so I just include it and use it?
The program works just fine.
Hello world!
Done
Is this considered bad?
Some programmers consider it bad style to use C library functions when there are superior C++ library functions available. However, there are cases where it is better to use the C library functions.
Could undefined behavior arise?
Probably not. The C++ standard library incorporates almost the entire C standard library (with a few minor changes), so calls to C library functions from C++ are well-defined. As for functions such as write, their behaviour is defined by POSIX.
Is C code "compatible" with C++ so I just include it and use it?
For standard C library headers, yes. For implementation headers, typically yes; they are usually designed so that they can be validly included into C++ programs. For other headers... maybe. Not all C code is valid C++, but the degree of compatibility is high.
C++ forked from C a long time so, and the two languages have evolved independently.
The C++ standard describes deliberate incompatibilities that were introduced to C++ relative to the C standard from which it derived: http://eel.is/c++draft/diff.iso.
The mistake people make is in thinking this is a complete list of differences. C itself has evolved, and while parts of C99 were incorporated in recent versions of C++ not all have (VLAs, flexible array members, compound literals, ...).
C11 made the gap much wider, from small things like the removal of gets (still included in C++17) to things like bounds checking interfaces, threading support, and c-variants of c++ features like _the Static_assert keyword.
So for the most part you can get away with old-C-ish code in a C++ program, a few small changes that will cause compiler errors, a couple that might not, and nearly 20 years of C advances that you only have partial accesso to.
If you really want to write C-like code, consider writing C code and taking advantage of the full set of language improvements available in that language. The result will be much higher quality code than the rubbish you'll knock up restricting yourself to C++'s subset of C.
Gala,
Yes this is fine. C++ is a superset of C, you can blend the two with ease. In fact, many older programmers (like me) write C++ with a C style. In this style, printf, strcpy, no templates, RogueWave rather than stl, etc are used with C++ classes. Sometimes this is termed 'C with classes'.
--Matt

What is std:: used in conjunction with aside from cout and endl?

My program originally used using namespace std; but I have heard from numerous people that this is bad programming practice so I want to break the habit. I changed all of the couts and endls in my program to std::cout and std::endl;.
Aside from cout and endl, what uses the namespace std? For example: I have vectors and strings in my program; do they use std::?
A list would be nice if it's not too long or too much of a hassle.
For example: I have vectors and strings in my program; do they use std::?
Yes. Vectors and strings are part of the standard library. The members of the std namespace are in the standard library.
A list would be nice if it's not too long or too much of a hassle.
I can't give you a long, concise list. But I can show you how to find the members of the standard library. For example, take your other question. Are strings and vectors part of the standard library?
http://en.cppreference.com/w/
If we go here, click on 'Strings library' we can infact see the different types of strings we can employ in our C++ program. This process is the same for vectors, under the 'Containers library' section we can see vector, list, map etc.
If you have an IDE, you can also view the members of the standard library by prefacing your statement with std:: -
Although you do have to have a matching header file included to see members of the standard library, the headers are named as you'd expect,
#include <list>
#include <vector>
#include <string>
Dumping the entire std namespace into your program is perhaps not the wisest choice, but I wouldn't be troubled by using specific elements from std. So instead of writing using namespace std you can use using std::cout, using std::endl, etc. Having to qualify lots and lots of code does not, in my opinion, help readability.
As for what's in std, it's a very long list, including all of STL. Just try to compile and see where the compiler complains.
In short:
For everything in the C++ standard library.
That includes datastructures, algorithms, input output functions, type_traits, string manipulation, almost everything you can find in the C standard library... . You can find a list e.g. at cppreference.com
Almost all types and functions provided by the C++ standard library are in namespace std. Roughly speaking, this includes everything in standard headers without a .h in their filename - like <vector>, <iostream> (which brings in std::cout), <string> (std::string), <algorithm> (standard algorithms), and EVERY other standard C++ header file. It does not include the C standard library (<stdio.h>, <stdlib.h>, etc) although these do have equivalents in the C++ standard library (<cstdio>, <cstdlib>, etc) which do place their declarations into namespace std.
There is no point in writing a list. If you are using any part of the C++ standard library, you will be working with namespace std. So any reference of the C++ standard library is the defacto list.
There are a couple of exceptions (e.g. names in the standard headers that are specified to be macros) but those are rare.

Updating legacy C code headers to C++ stdlib

Inherited a slew of legacy C code, and am in the process of porting it to compile on Linux with GCC (g++). Since we are going to be using C++ in the future and I'm fixing the "custom" library header files anyways (and compiler warnings), is it safe to update the old C headers to use the newer C++ style ones.
So things like
#include <cstdlib>
Instead of
#include <stdlib.h>
To my knowledge the only difference between the two is that cstdlib has things in the std:: namespace.
Would anything make this a bad idea?
Your code may change in very subtle ways, due to the fact that the C++ standard headers use overloading where C used different names. This is most likely to cause trouble with cmath.
stdlib.h isn't going anywhere, so feel free to keep using it.
For example, compare:
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <math.h>
int main(void)
{
double x = -2;
cout << (3/abs(x)) << endl;
return 0;
}
The results before and after switching to C++ headers are very different, even though the exact same C++ compiler and options are used in both cases.
They're exactly the same (on most systems) except for the namespace thing.