C + + input and output

Source: Internet
Author: User

1 overview

Both C and C + + do not have inputs and outputs built into the language, and C + + puts the input and output solutions in the class library (classes defined in headers iostream and FStream)

C + + programs treat input and output as byte streams. Flow serves as a bridge between program and stream source targets.

Derived relationships for C + + input and Output classes: Ios_base, iOS, Istream/ostream, iostream

CIN and cout are objects

2 cout

2.1 << Insert operator

There are 3 ways to use the Insert operator: 1. A cout accepted type (int char long (including signed/unsigned) float double long double), including numeric/variable/dereference pointer/array ; 2.char array name or char pointer (must be char */signed char */unsigned char* instead of other type) 3. Quoted string

1     inti =999;2     int*p = &i;3cout<<*p<<"  "<<p<<Endl;4     Char*a ="Hellow";5cout<<*a<<"  "<<a<<Endl;6     Charname[Ten] =" World";7cout<<name<<endl;

Output Result:

That is, the pointer to a non-char type must be cout<<*p, otherwise cout<<p is just the address of the output p, and a pointer of type char, cout<<*p equivalent to output P[0], is cout<< P output p points to the entire contents of the string because the cout<< prototype provides a separate char pointer type for the char type, and a string array of type Charl is similar. All in all, a pointer or array name of a non-char type is handled normally, and a pointer or array name of type char is treated directly as content

2.2 Stitching output

The << insert operator can be spliced, and the method can also be spliced, such as Cout.pur (' I '). Put (' T ')

2.3 cout.put (); Cout.write ()

Put output character, receive a parameter of type char, or convert numeric parameter to char value

The write output string, which receives two parameters, is a prototype:

1 basic_ostream<chart,traints>& write (const char_type* s, streamsize N);

Write does not stop when a null character is encountered, and write continues to print even if the boundary is exceeded

Cout.put ('A') <<Endl; Cout.put ('A'+0x20) <<Endl; Cout.put ( $) <<Endl; Char*name ="Hellow"; Char*name1 =" World"; Cout.write (Name, A) <<endl;

2.4 cout formatted value

For char, numeric integer, the string is displayed in the field corresponding to its width, for floating-point numbers, shown as 6 bits (if 6 bits enough), not enough of the end of 0 is not displayed, when the exponent >=6 or <=-5 in scientific notation, otherwise displayed in fixed-point notation

1     floati =1.2;2     floatj =1.23456789;3     floatm =123456789; The default intensive reading is 6-bit4     floatn =123456.789;5cout<<i<<Endl;6cout<<j<<Endl;7cout<<m<<Endl;8cout<<n<<Endl;9cout<< (n * 1e3) <<endl;

The last line is equal to 1 times 10 of the 3 square, when the exponent is greater than 6, expressed by scientific counting method

Output decimal:cout<<dec; octal:cout<<oct; 16 binary: Cout<

2.5 cout.width (); Cout.fill (); Cout.precision ()

The width () method has two types of prototypes:

int width (); Returns the current setting of the character width

int width (int i); Sets the width to I and returns the previous character width

Note: The width method affects only one item that is displayed next, then restores the field width to the default, and C + + never truncates the data, and when the width is not enough it increases the width, and it is more important to show all the data than to keep the column neat.

1     intW = cout.width ( -); 2cout <<"Default Field width ="<< W <<": \ n"; 3      for(inti =1; I <=Ten; i++)4     {5cout<<"Width:";6 cout.width (i);7cout<<i<<Endl;8}

Because width () returns to the previous width, the default width of 0 is returned, and the program indicates that width () affects only one item that is displayed next

By default, spaces are populated with unused portions of the field, and you can use the Fill () method to modify the fill, such as filling the writing cout.fill (' * ') with *, with a scope that lasts until you change it.

Cout.precision () is the method of setting the precision, by default the precision refers to the total number of digits, in fixed-point mode (fixed) and scientific mode of precision refers to the number of digits after the decimal point, the scope is always valid, by default, the accuracy is 6 bits

1     Cout.precision (5); 2     float 1.2345678 ; 3     cout<<i<<Endl; 4     cout<<Fixed

2.6 cout.setf (); COUT.SETF () and standard controls for C + +

This type of function can control a variety of formatting features, the former is used to format, the latter is used to eliminate the format, such as: COUT.SETF (Hios_base::showpoint), used to display the end of the decimal point, but this is more cumbersome, so C + + provides a number of control characters, Ability to call SETF ()

Standard controls are used directly behind the insert operator, and some common standard controls are:

cout<<showbase;  cout<<noshowbase; Using/not using C + + prefixes for output

cout<<showpoint;  cout<<noshowpoint; Show/Don't show end decimal point

cout<<showpos;        cout<<unshowpos; For positive numbers, show/Don't show +

cout<<left;                           cout<<right; Left justified/right justified

cout<<dec; cout<<oct;           cout<

cout<<fixed;                   cout<<scientific; Using fixed-point/scientific counting method

2.7 Iomanip Header File

Mainly provides three functions: Setprecision (); Set Precision

Setfill (); Fill character

SETW (); Set width

It is convenient to join the cout statement.

3 cin

3.1 >> decimation operators

The cin>>______ space must be the type that CIN accepts (int char long (including signed/unsigned) float double long double), which can be a variable, reference, dereference pointer, can also be a class or struct member

As with cout, separate overloads are made for pointers and arrays of type char, and you can use the array name or pointer directly, whereas for pointers of non-char types, you must dereference

1     int A; 2     int *p = &A; 3     cin>>*p; 4     cout<<*p<<Endl; 5     Char name[]; 6     cin>>name; 7     cout<<name<<endl;

3.2 cin>> Check input

Reads everything from a non-whitespace character to the first character that does not match the target type. A mismatch between the input and the expected format causes the cin>> result to be false

Enter an end condition: to the first character that does not match the target type (for example, enter, Space, TAB key)

Handling of Terminator: Discard Terminator (Enter, Space, TAB) in the buffer that makes the input end

3.3 Cin.get (); Cin.getline ();

Cin.get (); Cin.getline () provides input that does not skip whitespace

Cin.get () Three prototypes commonly used: Cin.get (), Cin.get (char), cin.get (char *, int)

Single character input can be used in the first two,Ch=cin.get () and cin.get (CH) are equivalent, enter and display a string with a space

1     Char ch; 2      while (ch = cin. Get ' \ n ' )3         cout<<ch;

String Access can be Cin.get (char *, int) or cin.getline (char *, int)

Input end Condition: Stop reading when reading to a specified number of characters or line breaks

Handling of Terminator: Get () leaves the newline character in the input stream, so that the next input operation first sees the book newline character, while Getline () extracts and discards the newline character in the input stream, and can use a cin.get () to process line breaks left in the input stream when reading a string with Get ()

1     Cin. Get (Array1,ten); 2     Cin. Get (); 3     Cin. Get (Array2,ten);

Cin.get (Array_Name, arsize) when the input string is very long, it does not cause an error in the CIN function, and subsequent CIN operations continue, just fetching data directly from the buffer. However, cin.getline () will cause an error in the CIN function when the input is very long, and the subsequent CIN operation will no longer execute

3.4 Cin.peek ()

Returns the next character in the input, but does not extract the characters from the input stream, that is, view only, not extract. such as shielding space

1  while ' ' )2     cin.  Get();

3.5 Cin.ignore (); Cin.read (); Cin.gcount ();

Cin.ignore (), receives two parameters, such as: Cin.ignore ($, ' \ n ') reads and discards 200 characters in the input stream or reaches the first line break

Cin.read (), receives two parameters, reads the specified number of bytes, and stores them in the specified location, char gross[144] cin.read (gross,144), usually with Cout.write ()

Cin.gcount (), returns the number of characters read by the last unformatted extraction method, meaning that characters read by get (), getline (), ignore (), and the Read () method are counted instead of >>

1cout<<"Enter a section of characters:";2Cin.ignore (5,'\ n');3     Charnum[ -];4Cin.read (NUM,Ten);5cout<<"number of characters extracted:"<<cin.gcount () <<Endl;6Cout.write (NUM,Ten) <<endl;

C + + input and output

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.