C ++ BASICS (cout/cin)

Source: Internet
Author: User

 

The standard output stream in the C ++ programming language interchange stream, which must be supported by iostream. h. Read as "c out ".
Directory

Example
Case Analysis
Skill Application
Cout Controller
Other information
Example # include <iostream>
Using namespace std;
Int main ()
{
Int;
Cout <"enter a number and press enter to end" <endl;
Cin>;
Cout <a <endl;
Return 0;
}
The number entered by the user is saved by cin in variable a and output through cout.
# Include <iostream>
Using namespace std;
Int main ()
{
Cout <"Hello, World! "<Endl;
Return 0;
} // Hello World example
Since I have learned C before, the rest of this Code is still "normal" in my opinion, but cout is quite unique: neither a function, it does not seem that C ++ specifically stipulates "statements" such as if and for with special syntax ". Because it is only a preliminary introduction, the book simply says that cout is a "standard input/output stream" Object in C ++ ...... This is a very profound term for me. This is not complete, and then we met cin ...... I am not sure what I want to do, and I am very scared when I use them. I want to escape from the concise printf () in the C era. After all, I can say that I am calling a function. So there's a long string of <,>. What's the matter? I have always wanted to treat them as keywords, but they are not. They are actually made in C ++! But when printf () was used more often, some people began to criticize my program "the C language trace is too heavy "......
Later, with the further study, I finally understood cout/cin/cerr /... the tricks: those things are just changing the way they are "cool", but in the end they are still called functions. However, this function is special and uses Operator overloading. To be exact, the following uses cout as an example) the <operator is overloaded. Now let's show it the true nature of the function. Please refer to HelloWorld! Equivalent version:
# Include <iostream>
Using namespace std;
Int main ()
{
Cout. operator <("Hello, World! ");
Cout. operator <(endl );
Return 0;
}
Compiling and running. The result is no different from that of the classic version. The above program should be easier to understand: cout is an iostream class object, which has a member operator function operator <, each time a call is made, it will output something to the output device (usually the screen. Well, here is a question: why can the operator function <accept different types of data, such as integer, floating point, string, and even pointer?
I guess you have already guessed it. That's right, it's to use the operator to reload it. Operator Functions are basically the same as general functions and can be reloaded as needed. The designers of the standard library have already customized iostream: operator <for the overloaded versions of various C ++ basic data types, this allows beginners to enjoy cout <"Hello, World! "<Endl;
Cout. operator <("Hello, World! "). Operator <(endl );
Is considered as "strongly equivalent ". Can I write it like this? Confirm with the compiler ...... OK, NoProblem!
Skill Application well, we have basically seen the essence of cout. Now we can try to implement a simplified version (Lite) of cout by ourselves, we name the cout object myout, and the class to which the myout object belongs is MyOutstream. What we need to do is to reload a series of operator operators of different types for the MyOutstream class <operator function. For simplicity, Here we only implement the integer and string types (char *). In order to express the disconnection from iostream, we no longer use the header file iostream, but use the printf function in the old stdio for output. The program is very simple, including the complete main function, which is listed as follows:
# Include // stdio. h In C and some ancient C ++. The new standard aims to make the standard library
// The header file is different from the user header file. We recommend that you do not use an extension.
// Version. For the original C library, c must be added before the header file name without the extension.
Class MyOutstream
{
Public:
Const MyOutstream & operator <(int value) const; // overload of Integer Variables
Const MyOutstream & operator <(char * str) const; // reload the string type
};
Const MyOutstream & MyOutstream: operator <(int value) const
{
Printf ("% d", value );
Return * this; // pay attention to this return ......
}
Const MyOutstream & MyOutstream: operator <(char * str) const
{
Printf ("% s", str );
Return * this; // Similarly, pay attention to it here ......
}
MyOutstream myout; // Global Object myout for our services anytime, anywhere
Int main ()
{
Int a = 2003;
Char * myStr = "Hello, World! ";
Myout <myStr <"\ n ";
Return 0;
}
The myout we have defined has already taken shape and can work for us. Note in the program that we should pay special attention to the following two points: operator <after the function is executed, it always returns a reference of itself, and the output has been completed. Why do we need to do this?
Remember that cout. operator <("Hello, World! "). Operator <(endl? Its implementation means that we can write
Cout <"Hello, World! "<Endl;
Instead
Cout <"Hello, World! ";
Cout <endl;
Why can it be connected and written like this? Let's analyze: In the execution order, the system first calls cout. operator <("Hello, World! "), Then? Then cout. operator <will return it, that is, the last line of the function will contain a statement similar to return * this, so cout. operator <("Hello, World! ") The call result returns cout, followed. operator <(endl), which is equivalent to cout. operator <(endl) -- then the next output will be made. If there are many <operators down, the call will continue ...... Wow, isn't it smart? Now you understand the secrets of MyOutstream: operator <the last line!
Pay attention to the most exciting line in the main function:
Myout <"\ n"
We know that the last "\ n" can implement a line feed, but we always intentionally or unintentionally let us use endl in the C ++ tutorial, the two seem to be the same-what exactly is mysterious? In the book, The endl is a manipulator, which not only implements line feed operations, but also refreshes the output buffer. What does it mean? After the output operation, the data is not immediately transmitted to the output device, but first enters a buffer zone. When the appropriate time (such as when the device is idle), the data is passed in by the buffer zone, you can also force refresh by using the operator flush, ends, or unitbuf:
Cout <"Hello, World! "<" Flush the screen now !!! "<Flush;
In this way, when the program runs to operator <(flush), it is possible that the previous string data is still in the buffer rather than on the screen, but after the operator <(flush) is executed, the program will forcibly move all the data in the buffer zone to the output device and clear it. The manipulator endl is equivalent to <"\ n" <flush;
However, the screen may show that manual refresh is not much different. However, output objects such as files are not the same: too frequent refresh means that writing a disk always affects the speed. Therefore, it is usually written to a certain number of bytes before refreshing. How can this problem be solved? These operators are used.
Cout control letter description
Base number of dec 10
The hex base number is 16.
Oct base number is 8
Setfill (c) is set to c
Setprecision (n) sets the precision of a real number to n bits
Setw (n): Set the domain width to n characters.
Setiosflags (ios: fixed) fixed floating point display
Setiosflags (ios: scientific) index Representation
Setiosflags (ios: left) left alignment
Setiosflags (ios: right) right-aligned
Setiosflags (ios: skipws) Ignore leading Blank
Setiosflags (ios: uppercase) hexadecimal number uppercase output
Setiosflags (ios: lowercase) hexadecimal lowercase output
Other information: C ++ iostream family
Okay, so much. What are the advantages of C ++'s iostream family compared with C's printf/scanf family? First, data processing is safer and more intelligent. Think about how to deal with int, float, and other specifiers such as "% d" and "% f" in printf, in case of errors, it will still die. Secondly, it is more scalable: If I define a new Complex category Complex, printf can't do anything about it, at most it can only output the real and virtual parts separately, iostream's <,> operators can be reloaded. You only need to reload the related operators. Moreover, the stream style is also concise, isn't it? CIN

The standard input stream in the C ++ programming language interchange stream requires iostream. h support and # include <iostream. h> (the new version of the compiler is # include <iostream>). Read "see in", Pinyin "si yin ",
Cin indicates a standard input device. The extract operator ">" is used to obtain data from the device keyboard, send the data to the input stream object cin, and then send the data to the memory. Using cin, you can obtain multiple input values from the keyboard. The specific format is as follows:
Cin> Expression 1> Expression 2...> Expression n;
Example:
# Include <iostream. h>
Int main ()
{
Int;
Cout <"enter a number and press enter to end" <endl;
Cin>;
Cout <a <endl;
Return 0;
}
The number entered by the user is saved by cin in variable a and output through cout.
# Include <iostream>
Using namespace std;
Int main ()
{
Int a = ios_base: failbit; Generally, ios_base: new ios: old-fashioned
Cout <;
System ("pause ");
Return 0;
}
/*
Goodbit = 0 no error normal
Badbit = 1 fatal error irreparable
Eofbit = 2 end of File
Failbit = 4 input error can be recovered
*/
# Include <iostream>
Using namespace std;
Int main ()
{
Int a, B;
Cout <"a: _ \ B ";
Cin> a; // redundant characters may be missed in the buffer if char is input.
1. cin. clear (); // restore goodbit
Cin. sync (); // clear the buffer
2. cin. clear ();
Fflush (stdin );
3. cin. clear ();
Cin. ignore (number of times, 'character to end (here \ n) ') // the general number of times gets large enough for the terminator to take effect
Cout <"B: _ \ B ";
Cin> B;
Cout <"a =" <a <", B =" <B;
System ("pause ");
Return 0 ;}
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.