Summary of cout and CIN usage

Time:2020-9-17

cout

coutFor displaying messages on the screen, it should be short for console output. It isC++inostreamObject, which is encapsulated in the<iostream>Library, the name of the library definition is placed in the namespacestdMedium, socoutIs the full name ofstd::cout
coutIs classified as a stream object, which means that the. To display a message on the screen, you can send a string of characters tocout。 For example:

cout << "hello world!" ;  

If you want to usecout, need to include library<iostream>

Format control of cout output

in usecoutSome format control operators can be placed in statements to achieve different output effects.

Output numbers in different base numbers

coutIn the output number, the default is decimal mode, can also be usedhexoctdecTo control the base of the output, all three control characters are included in the<iostream>Library. For example:

using namespace std;
auto i = 65534;
cout.setf (IOS:: uppercase); // output in uppercase
Cout < hex < I < endl; // hexadecimal output (default is lower case letters)
Cout < OCT < I < endl; // octal output
Cout < Dec < I < endl; // decimal output
Cout < setbase (16) < I < endl; // output in hexadecimal

Among themsetiosflags(ios::uppercase)Indicates output in uppercase (default isios::lowercase), setbase(n)Method means output in N base, where n value is 8, 10 or 16, and other values have no output. Both functions are included in the library<iomanip>Medium.
usesetiosflags()You can use the|To set multiple bits at the same time, for example:

cout << setiosflags(ios::scientific | ios::showpos) << 12.01 << endl;

Controls the output of floating-point numbers

It can be done throughsetprecision(n)setiosflags(ios::fixed)orfixedRightcoutThe output accuracy is controlled. These controls are included in the library<iomanip>Library’sstdNamespace.

#include <iostream>
#include <climits>
#include <iomanip>

int main(void)
{
    using namespace std;
    system("chcp 65001");
    system("cls");

    double p = 1233.141592653;
    cout << p << endl;
    Cout < setprecision (3) < p < endl; // keep two decimal places
    cout << setprecision(15) << p << endl;
    cout << setiosflags(ios::fixed);
    cout << p << endl;
    cout << fixed << p << endl;
    return 0;
}

The operation results are as follows:

1233.14
1.23e+03
1233.141592653
1233.141592653000089
1233.141592653000089

Display decimal point and sign

In addition, you can also use thesetiosflags(ios::showpoint)To display the decimal point, usesetiosflags(ios::showpos)To display the sign. For example:

double i2 = 100;
double d2 = -3.14;
cout << setprecision(4);
Cout < < setiosflags (IOS:: showpoint); // display decimal point
cout << i2 << endl;
Cout < < setiostags (IOS:: showpos); // displays the sign
cout << d2 << "\t" << i2 << endl;

The output results are as follows:

100.0000
-3.1400   +100.0000

Six significant digits are displayed by default.

Set width and alignment

It can be done throughsetw(n)Function to set the width of the output. When the width is insufficient, the remaining space is filled with spaces. If the width exceeds the width, the set width is ignoredsetiosflags(ios::left|ios::right)To set the alignment. These are defined in<iomanip>In the librarystdNamespace. For example:

cout.fill(' ');
cout << setw(10) << 100 << setw(10) << 100 << endl;
cout << setiosflags(ios::left) << setw(10) << 100 << setw(10) << 100 << endl;
cout << setiosflags(ios::right) << setw(10) << 100 << setw(10) << 100 << endl;

The output results are as follows:

       100       100
100       100
       100       100

The output results are right aligned by default.

Set padding character

When the width is greater than the number of characters,coutBy default, spaces are used to fill the remaining space. You can usesetfill('*')To set other padding characters. For example:

cout << setfill('*') << setiosflags(ios::right) << setw(10) << 100 << setw(10) << 100 << endl;

Member functions using cout

ostreamClass also has some member functions, which can be accessed bycoutYou can also control the format output by calling them. Unlike the previous controls, using member functions affects all subsequent outputs that use the default format. As shown in the table below:

Member function Control character explain
precision(n) setprecision(n) Set the precision of output floating-point number to n
width(w) setw(w) Specifies that the output width is w characters
fill(c) setfill(c) When the output width is specified, the extra white space is filled with the character C
setf(flag) setiosflags(flag) Set the output format flag to 1
unset(flag) resetiosflags(flag) Set an output format flag to 0
cout.precision(5);
double x = 1123.23456;
cout << x << endl;

cout.width(20);
cout.fill('*');
cout << x << endl;

cin

cinIs the standard input stream object in C + +, which isistreamClass, contained in the<iostream>In the library,stdNamespace.cinIt is mainly used to read data from standard input, which refers to keyboard.
When we input a string from the keyboard, we need to press the Enter key to send the string into the buffer. The Enter key is also converted to a newline character, which is stored in thecinAnd is calculated as a character.
cinRead data is also read from the buffer. When the buffer is empty,cinOnce there is data, it triggers the function to read the data. So, when there is residual data in the buffer,cinInstead of asking for keyboard input, the function of.

Common reading methods of CIN

When usingcinWhen reading data from standard input, the following methods are commonly usedcin >>cin.get()cin.getline()

cin >>

cin >>Data can be read continuously from the keyboard, with spaces, tab keys, or line breaks as separators or terminators.
When reading data from a buffer, if the first character is a white space character,cin>>Ignores and clears it, continues to read the next character, and continues to wait if the buffer is empty. If the read is successful, the separator after the character is left in the buffer,cin >>No processing.

int a, b, c;
cin >> a >> b >> c;
cout << a << b << c << endl;

The above code will require us to input three numbers separated by blank space before the output is complete.
cin>>Equivalent tocin.operator>>()Call the member functionoperator>>()Read the data.
If you don’t want to skip the first white space, usenoskipwsFlow controller. As follows:

cin >> noskipws >> a;

cin.get()

This function has multiple versions of overloading. As follows:

int cin.get(); 
istream& cin.get(char& var);
istream& get(char* s, streamsize n);
istream& get(char* s, streamsize n, char delim);

Among themstreamsizeIs defined aslong longType.

int cin.get () and istream& cin.get (char& var)

Both versions read one character at a time.
For example, the following code:

char c1, c2;
c1 = cin.get();
cin.get(c2);
cout << c1 << '\t' << (int)c2 << endl;

Run, enter a, then enter, and the output is as follows:

a
a

Like the code above:

  • cin.get()When a single character is read from the buffer, it is read directly without ignoring the white space, so the variablec2A blank line is saved\r。 Its return value isintType. If successful, it will return the ASCII value of the read character. When encountering the end of file character, it will returnEOF, i.e-1。 In windows, you can use Ctrl + Z to enter the end of the file.
  • cin.get(char var)If successful, the returned iscinObject, so it can support chaining operations, such ascin.get(a).get(c)
  • have access tocin.get()To remove line breaks left over from the buffer.

use cin.get () read a line

cin.get()The last two overload forms of,

istream& get(char* s, streamsize n);
istream& get(char* s, streamsize n, char delim);

Can be used to read a line. The difference between the two versions is that the former ends with a newline character by default, while the latter can specify a terminator. In the parametersnRepresents the size of the target space.
For example, the following code:

#include <iostream>

int main(void)
{
    using namespace std;
    system("chcp 65001");
    system("cls");

    char arr1[100] = {NULL};
    cin.get(arr1, 100);
    char a;
    cin.get(a);
    cout << arr1 << " " << (int)a << endl;

    system("pause");
    return 0;
}

The result of running:

Hello World // input
hello world 10

From the above code, we can see that:

  • When reading a line, it stops reading when it encounters a newline character, but the newline character is not processed, and the newline character is still left in the input buffer.
  • Second usecin.get(a)Read line breaks into variablesaThe output value of ASCII code is 10. It’s the last line break left over.
  • When this method reads a line, it can only read the string into the C-style string, that ischar*, using C + +getline()Function to read a string into thestringType.

cin.getline Read a line

This function reads a string from the keyboard and ends with a specified terminator. It does not leave line breaks in the buffer. There are two overloaded versions of the function, as follows:

Istream & getline (char * s, streamsize count); // the default line break ends
Istream & getline (char * s, streamsize count, char delim); // delim specifies the terminator

For example, the following code:

#include <iostream>

int main(void)
{
    using namespace std;

    char arr1[100] {0};
    cin.getline(arr1, 100);
    cout << arr1 << endl;

    system("pause");
    return 0;
}

The conditional state of CIN

usecinWhen reading keyboard input, if there is an error,cinThe condition state is set. The condition state is defined as follows:

  • Goodbit: no error
  • Eofbit: end of file reached
  • Failbit: a non fatal I / O error that can be retrieved
  • Badbit: fatal I / O error, irreparable

These condition states have corresponding member functions, which can be used to set and read the current condition states. These member functions are as follows:

function explain
cin.eof() Returns true if eofbit of stream CIN is 1
cin.fail() Returns true if the failbit bit bit of the stream CIN is 1
cin.bad() True if the badbit bit bit of the stream CIN is 1
cin.good() Returns true if the goodbit bit bit of the stream CIN is 1
cin.clear(flags) Clear the status flag bit, set the given flag bit flags to 0, and there is no return value. If there is no parameter, then all non good states will be cleared
cin.setstate(flags) Set the corresponding flags to 1, no return value
cin.rdstate() Returns to the current state. The return value type is iostate
cin.ignore() It has two parameters, the first is an integer and the second is a char type. It means that the number of characters specified by the first parameter is extracted from the input stream CIN, and then these characters are ignored. If the extracted number reaches the specified value or the character is equal to the character specified by the second parameter, the function will terminate. Otherwise, continue to wait until one of the two conditions is met. The second parameter defaults to EOF

For example, the following code:

#include <iostream>

int main(void)
{
    using namespace std;
    system("chcp 65001");
    system("cls");
    
    int a;
    while(true)
    {
        cin >> a;
        Cout < < "bit status: good ="<< cin.good () << ", eof=" <<  cin.eof () << ", bad=" <<  cin.bad () << ", fail=" <<  cin.fail () << endl;
        //At the end of the file, you can use Ctrl + Z
        if(cin.eof())
        {
            Cout < < end of file command < endl;
            exit(1);
        }
        if(cin.fail())
        {
            Cout < < < ". " << endl;
            cin.clear();
            cin.ignore (1000,'n '); // ignore everything that follows
            continue;
        }
    }
    system("pause");
    return 0;
}

Operation results:

1
Bit status: good = 1, EOF = 0, bad = 0, fail = 0
a
Bit status: good = 0, EOF = 0, bad = 0, fail = 1
Non numeric input.
^Z
Bit status: good = 0, EOF = 1, bad = 0, fail = 1
End of file command

We can see that after entering the correct type (int), the good bit flag is 1. The fail bit is set when non numeric is input. When the clear() function is used to clear the state, all bits except the good bit are set to 0.

Other functions for reading

These functions are notcinBut can also be used to read input.

Gets() function

gets()The function can read until a newline character or the end of a file is encountered. There is no upper limit on its reading, so the buffer must be large enough. It does not leave line breaks in the buffer. It is a library function of C language. Use as follows:

#include <iostream>

int main(void)
{
    using namespace std;

    char arr1[100] {0};
    gets(arr1);
    cout << arr1 << endl;

    system("pause");
    return 0;
}

Getchar() function

getchar()Read a character and return, can read white space, encountered newline character stop. Line breaks at the end are also handled.

#include <iostream>

int main(void)
{
    using namespace std;

    char c;
    c = getchar();
    cout << c << endl;

    system("pause");
    return 0;
}

Getline() function

getline()The function reads a whole line in thestdThe global function in the namespace. The parameters of this function use thestringType, so the declaration is in<string>Header file.
getline()Read a line from a standard input device and end when one of the following three situations occurs:

  1. End of file EOF.
  2. Row separator encountered.
  3. Input to the maximum.

There are two overloaded versions of this function:

Istream & getline (istream & is, string & STR); // lines are separated by newline character by default
Istream & getline (istream & is, string & STR, char delim); // specifies the separator

For example, the following code:

#include <iostream>

int main(void)
{
    using namespace std;
    
    while(true)
    {
        string str;
        getline(cin, str);
        cout << str << endl;
    }
    system("pause");
    return 0;
}

getline()When the function encounters the terminator, it will read the terminator into the specified string, and then replace the terminator with a null character.

Recommended Today

Explain module, import and export in JavaScript

Author: Tania rascia Crazy technology house Original text:https://www.taniarascia.com/j… In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescriptTag. […]