Why we do not use Printf and Scanf in C++? [duplicate] - c++

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Which I/O library do you use in your C++ code?
in C++ why we go for COUT and CIN

Because classes can overload the insertion operator <<
They cannot edit printf and add %Foo to know how to print a Foo class.

You can use them.
But the major problem is that they are not safe.
A lot of C code had problems because the format specifiers did not match the arguments and resulted in crashes etc.
// Example
char c;
scanf("%s",&c); // quite an easy mistake. Usually leads to a crash or something worse.
The C++ variants are type safe (in that the compiler guarantees that the type you are inputting into is the correct type at compile time) and the runtime does the work of actually moving the data.
A secondary reason is that it is a lot easier to define output functions in C++ (operator >> and <<) than in C (There was never a standardized way of naming streaming functions).
The third advantage is that a stream is not limited to console or file. There are several other types of stream that automatically work with the operator >> and << thus allowing you to generalize the streaming (or serialization) of objects in different circumstances.

Along with the ability to overload insertion and extraction operators for classes of your choice, cin and cout are type-safe, which scanf and printf are not -- e.g., a mismatch between the conversion format and actual type with printf is fairly common:
printf("%d\n", 1.0);
printf("%f\n", 1);
Neither of these is at all likely to produce useful output.

The old stdio functionality is in C++ for compatibility (and partially because the original C++ (cfront) was just a pre-processor for C so they were available anyway).
The newer I/O model found in C++ is a lot more flexible, allowing you to add types at will, which can be printed in a way defined by that type.
In other words, in an object oriented way.
Just like complex or rational numbers numbers (or address book entries or dictionary entries or any other non-basic type for that matter) should be self contained in a class that knows how to add, subtract or otherwise manipulate them separately from the base language, the printing of those objects should also be left to the class as well.
If you're worried about the verbosity of the C++ way, there's nothing stopping you from adding a fmt() method, returning a string, to your own data types to get around that problem, something like:
std::cout << name.fmt('left',15) // [Pax Diablo ]
<< " " << age.fmt(4) // [ 45]
<< " " << score.fmt(3,2) // [100.00]
<< std::endl;
for sizes and/or justifications.
It's more coding on your part within the class but it is an option if you're really adverse to the setfill and setw stuff.
However, since you'll almost certainly have your formatting code in a function for each type of output (if you're smart), it'll be isolated in one area. I'd just suck it up and learn the C++ way of doing things.

The C++ syntax is supposed to be easier but, frankly, I never adopted it. Besides, I do Windows programming, not console, so neither cout or printf are of much use. But sprintf and it's variations are.

Related

What might be the intention of printing a stream to itself?

I am attempting to build a third-party C++ code base in which there are several places where an attempt is made to print an output stream to itself. This example demonstrates an expression of the same form:
#include <iostream>
int main(void) {
std::cout << std::cout << "Say what?" << std::endl;
return 0;
}
I find that without any options, g++ 4.8.5 accepts that code with zero complaints, but g++ 8.2.1 rejects it with a good old "no match for ‘operator<<’" error.
I understand the error. What I want to know is whether there is any reason to think that it was ever anything other than an error -- was there a C++ version or a widely used C++ compiler that would do something useful with such code? Although it accepts the code, g++ 4.8.5 is not such a compiler in my book because the program it builds evaluates the first << operation simply by outputting a hexadecimal number of unclear significance.
I have considered that it might be a simple typo, maybe magnified by copy & paste. For example, perhaps the second std::cout was an accidental duplicate of the first, or perhaps it was meant to be std::endl, instead. However, in a different source file in the same code base I see the same idiom of an output stream being printed to itself applied to objects of type std::stringstream, which suggests to me that it might be intentional.
My overall objective is to decide how best to fix the code.
What might be the intention of printing a stream to itself?
It is probably unintentional, or the intention itself was a mistake.
The difference between the GCC versions is the default dialect of C++ that they use. The newer GCC defaults to c++11 or newer. The program should compile with the newer compiler as long as you use a pre-C++11 dialect.
The change in C++11 was the removal of implicit conversion from std::basic_ios to void*. The purpose of this conversion was to check for failure state of the stream: null signified a failed stream while non-null signified a valid stream which allows the pattern if(stream >> input). In C++11 the conversion was replaced with explicit conversion to bool. Since the new conversion is explicit, it won't be applied to inserting a stream into stream. This was a backwards incompatible change which was presumably considered to not be a problem since the now-incompatible ways of using the conversion (such as the example) would have had no practical uses. In fact, it is useful to get a compilation error when doing something that has no practical use.
My overall objective is to decide how best to fix the code.
Probably just remove the insertion of cout into cout. If you're concerned that the output must remain same because it might be parsed by another program, then you can output any non-zero hex number to keep the output same for the sake of compatibility.

C vs C++ file handling

I have been working in C and C++ and when it comes to file handling I get confused. Let me state the things I know.
In C, we use functions:
fopen, fclose, fwrite, fread, ftell, fseek, fprintf, fscanf, feof, fileno, fgets, fputs, fgetc, fputc.
FILE *fp for file pointer.
Modes like r, w, a
I know when to use these functions (Hope I didn't miss anything important).
In C++, we use functions / operators:
fstream f
f.open, f.close, f>>, f<<, f.seekg, f.seekp, f.tellg, f.tellp, f.read, f.write, f.eof.
Modes like ios::in, ios::out, ios::bin , etc...
So is it possible (recommended) to use C compatible file operations in C++?
Which is more widely used and why?
Is there anything other than these that I should be aware of?
Sometimes there's existing code expecting one or the other that you need to interact with, which can affect your choice, but in general the C++ versions wouldn't have been introduced if there weren't issues with the C versions that they could fix. Improvements include:
RAII semantics, which means e.g. fstreams close the files they manage when they leave scope
modal ability to throw exceptions when errors occur, which can make for cleaner code focused on the typical/successful processing (see http://en.cppreference.com/w/cpp/io/basic_ios/exceptions for API function and example)
type safety, such that how input and output is performed is implicitly selected using the variable type involved
C-style I/O has potential for crashes: e.g. int my_int = 32; printf("%s", my_int);, where %s tells printf to expect a pointer to an ASCIIZ character buffer but my_int appears instead; firstly, the argument passing convention may mean ints are passed differently to const char*s, secondly sizeof int may not equal sizeof const char*, and finally, even if printf extracts 32 as a const char* at best it will just print random garbage from memory address 32 onwards until it coincidentally hits a NUL character - far more likely the process will lack permissions to read some of that memory and the program will crash. Modern C compilers can sometimes validate the format string against the provided arguments, reducing this risk.
extensibility for user-defined types (i.e. you can teach streams how to handle your own classes)
support for dynamically sizing receiving strings based on the actual input, whereas the C functions tend to need hard-coded maximum buffer sizes and loops in user code to assemble arbitrary sized input
Streams are also sometimes criticised for:
verbosity of formatting, particularly "io manipulators" setting width, precision, base, padding, compared to the printf-style format strings
a sometimes confusing mix of manipulators that persist their settings across multiple I/O operations and others that are reset after each operation
lack of convenience class for RAII pushing/saving and later popping/restoring the manipulator state
being slow, as Ben Voigt comments and documents here
The performance differences between printf()/fwrite style I/O and C++ IO streams formatting are very much implementation dependent.
Some implementations (visual C++ for instance), build their IO streams on top of FILE * objects and this tends to increase the run-time complexity of their implementation. Note, however, that there was no particular constraint to implement the library in this fashion.
In my own opinion, the benefits of C++ I/O are as follows:
Type safety.
Flexibility of implementation. Code can be written to do specific formatting or input to or from a generic ostream or istream object. The application can then invoke this code with any kind of derived stream object. If the code that I have written and tested against a file now needs to be applied to a socket, a serial port, or some other kind of internal stream, you can create a stream implementation specific to that kind of I/O. Extending the C style I/O in this fashion is not even close to possible.
Flexibility in locale settings: the C approach of using a single global locale is, in my opinion, seriously flawed. I have experienced cases where I invoked library code (a DLL) that changed the global locale settings underneath my code and completely messed up my output. A C++ stream allows you to imbue() any locale to a stream object.
An interesting critical comparison can be found here.
C++ FQA io
Not exactly polite, but makes to think...
Disclaimer
The C++ FQA (that is a critical response to the C++ FAQ) is often considered by the C++ community a "stupid joke issued by a silly guy the even don't understand what C++ is or wants to be"(cit. from the FQA itself).
These kind of argumentation are often used to flame (or escape from) religion battles between C++ believers, Others languages believers or language atheists each in his own humble opinion convinced to be in something superior to the other.
I'm not interested in such battles, I just like to stimulate critical reasoning about the pros and cons argumentation. The C++ FQA -in this sens- has the advantage to place both the FQA and the FAQ one over the other, allowing an immediate comparison. And that the only reason why I referenced it.
Following TonyD comments, below (tanks for them, I makes me clear my intention need a clarification...), it must be noted that the OP is not just discussing the << and >> (I just talk about them in my comments just for brevity) but the entire function-set that makes up the I/O model of C and C++.
With this idea in mind, think also to other "imperative" languages (Java, Python, D ...) and you'll see they are all more conformant to the C model than C++. Sometimes making it even type safe (what the C model is not, and that's its major drawback).
What my point is all about
At the time C++ came along as mainstream (1996 or so) the <iostream.h> library (note the ".h": pre-ISO) was in a language where templates where not yet fully available, and, essentially, no type-safe support for varadic functions (we have to wait until C++11 to get them), but with type-safe overloaded functions.
The idea of oveloading << retuning it's first parameter over and over is -in fact- a way to chain a variable set of arguments using only a binary function, that can be overload in a type-safe manner. That idea extends to whatever "state management function" (like width() or precision()) through manipulators (like setw) appear as a natural consequence. This points -despite of what you may thing to the FQA author- are real facts. And is also a matter of fact that FQA is the only site I found that talks about it.
That said, years later, when the D language was designed starting offering varadic templates, the writef function was added in the D standard library providing a printf-like syntax, but also being perfectly type-safe. (see here)
Nowadays C++11 also have varadic templates ... so the same approach can be putted in place just in the same way.
Moral of the story
Both C++ and C io models appear "outdated" respect to a modern programming style.
C retain speed, C++ type safety and a "more flexible abstraction for localization" (but I wonder how many C++ programmers are in the world that are aware of locales and facets...) at a runtime-cost (jut track with a debugger the << of a number, going through stream, buffer locale and facet ... and all the related virtual functions!).
The C model, is also easily extensible to parametric messages (the one the order of the parameters depends on the localization of the text they are in) with format strings like
#1%d #2%i allowing scrpting like "text #2%i text #1%d ..."
The C++ model has no concept of "format string": the parameter order is fixed and itermixed with the text.
But C++11 varadic templates can be used to provide a support that:
can offer both compile-time and run-time locale selection
can offer both compile-time and run-time parametric order
can offer compile-time parameter type safety
... all using a simple format string methodology.
Is it time to standardize a new C++ i/o model ?

C-like procedures in C++?

Does the C++ correct programming style demand writing all your code with classes or are C-like procedures allowed ? If I were to give some code to someone else, would it be accepted as C++ just because it has std::vector and std::string (instead of char *) inside, or everything has to be a class?
eg:
int number = 204;
std::string result = my_procedure(number);
OR
MyClass machine;
std::string result = machine.get(number);
Are there cases where the programmer, will have to, or is allowed to have C-like procedures in some of his source code ? Did you ever had to do something like that?
In the context of this question where does the margin between C and C++ exist (if any)?
I hope my question is clear and inline with the rules.
It's certainly OK to have free functions in your code -- this is a matter of architecture, not of "++ness". For small programs it doesn't even make sense to go all-in with classes, as OO is really a tool to manage complexity. If the complexity isn't there to begin with, why bother?
Your second question, where is the line drawn, doesn't have a short answer. The obvious one is that the line is drawn in all places where the C standard differs from the one for C++. But if you are looking for a list of high-level language features that C++ has and C does not, here are some of them:
Class types and OO (of course)
The STL
Function/operator overloading
References
Templates
new/delete to manage memory
C++ is a multi-paradigm language, where OO, procedural, generic/generative and - to a lesser (but increasing with C++0x) extent functional - are among the paradigms. You should use whichever is the best fit for the problem: you want the code to be easy to get and keep right, and hard to stuff up.
The utility of classes is in packaging data (state) along with the related functions. If your wordify function doesn't need to retain any state between calls, then there's no need to use a class/object. That said, if you can predict that you will soon want to have state, then it may be useful to start with a class so that the client code doesn't need to change as much.
For example, imagine adding a parameter to the function to specify whether the output should be "first", "second" instead of "one", "two". You want the behaviour to be set once and remembered, but somewhere else in the application some other code may also use the functionality but prefer the other setting. It's a good idea to use an object to hold the state and arrange it so each object's lifetime and accessibility aligns with the code that will use it.
EDIT:
In the context of this question where does the margin between C and C++ exist (if any)?
C++ just gives you a richer set of ways to tackle your programming tasks, each with their necessary pros and cons. There are plenty of times when the best way is still the same way it would have been done in C. It would be perverse for a C++ programmer to choose a worse way simply because it was only possible in C++. Still, such choices exist at myriad levels, so it's common to have say a non-[class-]member function that takes a const std::string& parameter, combining the procedural function call with object-oriented data that's been generated by a template: it all works well together.
C++ allows a variety of programming styles, procedural code being one of them.
Which style to use depends on the problem you are trying to solve. The margin between C and C++ is are you compiling your code with a C++ compiler.
I do at times use procedural functions in my code. Sometimes it best solves the problem.
C++ code can still be valid C++ code even without classes. Classes are more of a feature, and are not required in every piece of code.
C++ is basically C with more features, so there isn't really a "margin" between the two languages.
If you read Stroustrup's Design and Evolution, you'll see that C++ was intended to support multiple programming styles. Use whichever one is most appropriate the problem (not the same as always just usnig the one you know.)
In legacy real world applications, there is often very little distinction. Some C++ code was originally C code nad then recompilied. Slowly it migrates to use C++ features to improve its quality.
In short, Yes, C++ code can be procedural. But you'll find it does differ from C code if you use C++ features where appropriate.
What is good practice needs to consider things like encapsulation, testability, and the comprehensibility of the client API.
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
string wordify(int n)
{
stringstream ss;
ss << n; // put the integer into the stream
return ss.str(); // return the string
}
int main()
{
string s1 = wordify(42);
string s2 = wordify(45678);
string s3 = wordify(-99);
cout << s1 << ' ' << s2 << ' ' << s3 << '\n';
}

C++ Streams vs. C-style IO?

I was coding some C++ for a small hobby project when I noticed that I'm using C-style operations to access IO (printf, fopen, etc.).
Is it considered "bad practice" to involve C functions in C++ projects? What are the advantages of using streams over C-style IO access?
This is an heated topic.
Some people prefer to use the C++ IO since they are type-safe (you can't have divergence between the type of the object and the type specified in the format string), and flow more naturally with the rest of the C++ way of coding.
However, there is also arguments for C IO functions (my personal favorites). Some of them are:
They integrate more easily with localisation, as the whole string to localise is not broken up in smaller strings, and with some implementation the localizer can reorder the order of the inserted value, move them in the string, ...
You can directly see the format of the text that will be written (this can be really hard with stream operators).
As there is no inlining, and only one instance of the printf function, the generated code is smaller (this can be important in embedded environment).
Faster than C++ function in some implementation.
Personally, I wouldn't consider it bad practice to use C stream in C++ code. Some organisations even recommend to use them over C++ stream. What I would consider bad style is to use both in the same project. Consistency is the key here I think.
As other have noted, in a relatively large project, you would probably not use them directly, but you would use a set of wrapper function (or classes), that would best fit your coding standard, and your needs (localisation, type safety, ...). You can use one or the other IO interface to implement this higher level interface, but you'll probably only use one.
Edit: adding some information about the advantage of printf formatting function family relating to the localisation. Please note that those information are only valid for some implementation.
You can use %m$ instead of % to reference parameter by index instead of referencing them sequentially. This can be used to reorder values in the formatted string. The following program will write Hello World! on the standard output.
#include <stdio.h>
int main() {
printf("%2$s %1$s\n", "World!", "Hello");
return 0;
}
Consider translating this C++ code:
if (nb_files_deleted == 1)
stream << "One file ";
else
stream << nb_file_deleted << " files ";
stream << removed from directory \"" << directory << "\"\n";
This can be really hard. With printf (and a library like gettext to handle the localization), the code is not mixed with the string. We can thus pass the string to the localization team, and won't have to update the code if there are special case in some language (in some language, if count of object is 0, you use a plural form, in other language, there are three forms one for singular, one when there is two object and a plural form, ...).
printf (ngettext ("One file removed from directory \"%2$s\"",
"%1$d files removed from directory \"%2$s\"",
n),
n, dir);
printf and friends are hideously unsafe compared to <iostream>, and cannot be extended, plus of course fopen and friends have no RAII, which means that unless you've proved with a profiler that you definitely need the performance difference (that you've proved exists on your platform and in your code), you'd have to be an idiot to printf.
Edit: Localization is an interesting thing that I hadn't considered. I've never localized any code and cannot comment on the relative localizational ability of printf and <iostream>
Nothing can be considered bad practice if it has a definite purpose. I mean, if IO is the bottleneck of the program, then yes, C-style IO works faster than C++ IO. But if it is not, I would go with C++ stream approach. Cuz it's cuter :)
For a small hobby project I would probably go with the more type-safe C++ io streams.
Funny enough, I've never seen a non-trivial real-life project that uses either of them. In all cases we used some abstractions built on top of the native OS API for IO.
Advantages
Type safety: the argument types of C++ streaming operations are checked at compile time, while printf arguments are passed through ... causing undefined behaviour if they do not match the formatting.
Resource management: C++ stream objects have destructors to close file handles, free buffers, and what have you. C streams require you to remember to call fclose.
Disadvantages
Performance: this depends on the implementation, of course, but I've found formatting with C++ streams to be considerably slower than the equivalent printf formatting.
IMHO, a real C++ programmer tries to do things in idiomatic C++ way; the C converted programmer tries to cling on old ways of doing things. It has to do with readability and consistency.
For one, you don't have to convert C++ objects (notably strings) to C-compatible forms first.
Is it considered "bad practice" to involve C functions in C++ projects?
Usually, the file IO code should be encapsulated in a class or function implementation. I wouldn't consider any choices you make in the encapsulated implementations to be "bad practice", I reserve that term for what affects the user of your library or code (i.e. the interface). If you are exposing your file IO mechanism in the interface, then, IMO, it's bad practice whether you use IO stream or C-style IO functions.
I would rather say that C-style IO functions are (probably always) the worse choice.
What are the advantages of using streams over C-style IO access?
First, they integrate better with standard C++ constructs such as std::string. They integrate fairly well with STL <algorithms>. And they allow you to create encapsulated custom read/write operators (<< and >>) such that your custom classes almost look like primitive types when it comes to doing IO operations.
Finally, IO streams in C++ can use exception mechanism to report errors in the stream or read/write operations. These make the file IO code much nicer by avoid the terrible look of error-code mechanisms (sequence of if-statements and ugly while-loops, that check the error code after each operation).
As a general rule, you should prefer C++ operators, they're:
-- Type safe. You don't risk passing a double where the format
calls for an int.
-- Extensible. You can write your own inserters and
extracters, and use them.
-- Extensible. You can define your own manipulators (with
application specific logical meaning), and use them. If you
want to change the format of all of the WidgitNumber
(internally, an int) in your output, you change the
manipulator; you don't have to find all of the format
statements where %d is a WidgitNumber.
-- Extensible. You can write your own sinks and sources, and
these can forward to other sinks and sources, filtering or
expanding the input or output as desired.
(FWIW: I don't think I've ever written an application which
didn't use custom >> and << operators, custom manipulators, and
custom streambuf's.)
Is it considered "bad practice" to involve C functions in C++ projects?
No. C functions are often used in C++ projects. Regarding the streams, Google C++ Style Guide, for example, recommends using them only in limited cases such as "ad-hoc, local, human-readable, and targeted at other developers rather than end-users".
What are the advantages of using streams over C-style IO access?
The main advantages are type safety and extensibility. However C++ streams have serious flaws, see the answers to this question such as problems with localization, poor error reporting, code bloat and performance issues in some implementations.

Creating a cout function in C?

I assume most C++ compilers are written in assembly. Which makes them different languages entirely (I could be wrong). That being said if I were going to create a cout style function for plain old C, how would I do it? cout has some very impressive features take this snippet for example:
// endl not only prints a new line but also flushes the stream
cout << "Hello World!" << endl;
Which I'm pretty sure translates to this in C:
printf("Hello World!\n");
fflush(1); //stdout = 1
Next order of business, the << operators. In C++ this would be easy (operator overloading), but I can't think of a single way to do this in C.
It may help in thinking about this to translate between the "<<" operator syntax and the "operator<<" function syntax. Your C++ example is equivalent to this bit of C++ code:
operator<< ( operator<< (cout, "Hello World!"), endl);
The first thing that you should notice here is that there is not actually a lot of cleverness in cout at all. What is clever is the operator<< function -- specifically, the version of the operator<< function that takes a stream object (which is what cout is, but many other things are too) as its first argument. Or, even more precisely, the range of operator<< functions that take a stream object as the first argument, and take a particular thing as the second argument -- there's one for each type of object that you can put into the cout stream. You can see one of the C++ tricks in that syntax, too; the operator<< functions on stream objects always return the stream object that they were given, thereby allowing chaining of this nature.
In order to put C++ code into linkers and system ABIs that expect C-like function syntax, most C++ compilers "mangle" the function names, in order to encode in them the type of arguments that they have. (Also, of course, the "<<" isn't a valid C-like function name.) So, if you looked at the generated assembly for this bit of function, you'd see that the names of the two functions were different from each other -- they'd have suffixes indicating the argument types. You could do something like that manually:
operator_lshift__stream__endl(
operator_lshift__stream__string(cout, "Hello World!"), endl);
And there you've got something that you could implement in C.
That's right, because C does not have operator overloading, you cannot change the behaviour of the << operator, it will always do a bit shift, so there is no way to write 'cout' with the precise semantics it has in C++, in C.
Out of interest, g++ (GNU C++ Compiler) is written mostly in C.
C is actually a popular implementation language for C++ compilers and standard libraries (so is C++ itself, actually -- a concept sometimes known as self-hosting or bootstrapping a language), and you can study the whole sources of a rich, complex C++ standard library (plus extensions) here (sorry, this is gcc 3 -- can't find a gcc 4 source tree that's just as easily browseable online, though of course you can easily download those sources and study them on your local machine).
Personally, I would suggest starting instead with a good book, such as this one -- the sources will be much more meaningful to you once you've got a good grasp of all the obscure nooks and crannies of C++'s iostreams (as a bonus, the book also takes you on a guided tour through locales -- hold on to your hat!-).