When I used to learn C++, I always swallowed up dates to understand cin, cout and other things. Recently, I was reviewing C++ and IO chapters. I felt a little touched. So I plan to record them.
As the saying goes, a picture is better than a thousand words, which is not unreasonable. Let's look at the inheritance structure of basic IO classes.
When we write simple C++ code, we like to write # include < iostream >, which is actually the header file of IO stream, but using namespace std; it means using standard space, so we can use cin, cout, endl and so on.
Seen from the figure above, IO can actually be classified into three categories: IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO, IO
1. iostream class: Responsible for dealing with console input and output, which we are familiar with. Note: Actually, it can be differentiated into istream and ostream.
2. fstream class: Responsible for dealing with file input and output, which we have contacted. Note: Actually, it can be distinguished as ifstream and ofstream.
Stringstream class: Responsible for dealing with input and output on strings, which we haven't used yet. Note: Actually, it can be distinguished as: istringstream and ostringstream.
Next, let's study/review one by one.
iostream of IO
Objects of the iostream class, such as CIN and cout, are directly associated with console input and output. Let's look at the simplest program:
It's easy to understand.
2. fstream of IO class values
The object of fstream, which is related to the file, is familiar to us. Look at the code directly.
3. stringstream of IO
stringstream objects are associated with string objects in memory, writing to string objects, or reading from string objects.
Let's first look at this question and assume that the content of test.txt is:
lucy 123
lili 234 456
tom 222 456 535
jim 2345 675 34 654
The first word in each line is the name, and the number behind it is their bank card password. Of course, jim has four bank cards at most. Now, what should we do to achieve the following output?
lucy 123x
lili 234x 456x
tom 222x 456x 535x
jim 2345x 675x 34x 654x
Look directly at the procedure:
The result is ok.
Next, let's look at how to use istringstream to convert strings to values:
Of course, we can also format numbers into strings, as follows (the following program has problems):
It seems that the above connection is unsuccessful and should be replaced by: