Detailed usage of C ++ IO

Source: Internet
Author: User

Http://www.cnblogs.com/keam37/ keam all reprinted please indicate the source

This article describes the usage of functions contained in the <iostream>, <sstream>, <fstream>, and <iomanip> header files.

# Inclde <iostream>

Cin, cout, and cerr are the most basic input and output streams. They are operated by the operators "<" and "> ".

For example, read two strings from the keyboard and then merge them into the output

string s1,s2;cin>>s1>>s2;cout<<s1+' '+s2;if(!cin)cerr<<"input error";

 

Run the following input:

Hello

Keambar

The output is as follows:

Hello keambar

If you directly enter the file Terminator ctrl + z

"Input error" is output"

 

Here, it corresponds to if (! Cin) is relatedCondition status of stream manipulation

There are several statuses (flag)

Badbit indicates that the stream has crashed.

Failbit indicates that an IO operation fails.

Eofbif indicates that the stream reaches the end of the file

Goodbit value is 0, indicating no error

Define istream s; // s is an input stream

S. bad ()Corresponding to badbit. If badbit is set, true is returned;

S. eof ()Corresponding to the eofbit status, as shown above;

S. fai ()Corresponding to failbit, as shown above;

S. good ()Corresponds to goodbit, as shown above;

S. clear ()Resets all error states. If a parameter such as s. clear (failbit) is added, only the failbit is reset;

S. setstate (flag)Resets the status of stream s to a given status;

S. rdstate ()Returns the status of the current s stream. The returned value is flag;

The following example is from C ++ primer:

 

Auto old_state = cin. rdstate (); // remember the current state of cin. clear (); // make the cin effective process_input (cin); // use cincin. setstate (old_state); // sets cin to the original state.

If the program crashes, the output buffer will not be refreshed, and the program execution result may not be output.

 

Method for refreshing the output buffer

Cout <"hi" <endl; add a line break to the output string and refresh it;

Cout <"hi" <flush; Output string, and then refresh;

Cout <"hi" <ends; add an empty character to the output string and refresh the string;

Unitbuf Operator

Cout <unitbuf // refresh immediately after all output operations;

Cout <nounitbuf // cancel the above operation

Associate input and output streams

By default, both cin and cerr are associated with cout. Therefore, cout is refreshed when you read cin or write cerr;

X. tie (& O) associates x with the output stream O;

X. tie () returns x's currently associated output stream pointer. If it is not associated with the output stream, a null pointer is returned;

Other operations

Cout. put (char ch)// Add the ch character to the output stream

Cin. putback (char ch)// Add the ch character to the input stream;

Cin. get (char * s, streamsize num, char delim)// Read the string from the cin stream, starting from the first pointer of the string, with the length of num, or reading the end of delim. The third parameter does not contain

Getline (cin, string s, char delim)// Read a row from the cin stream and put it into a string. If the row ends or the delim ends, the default value is delim = '\ n'

Cin. ignore (streamsize num = 1, int delim );// Number of reads from the cin stream. The length is num or the end of the delim reading. The default value is line feed;

// After get is used, you can useCin. gcount ()Returns the number of characters that have been read.

For example

 

char c[10];cin.get ( &c[0], 9 );cout << c << endl;cout << cin.gcount( ) << endl;

/* = /*

# Include <sstream>

Stringstream s; // defines a string stream s

Stringstream s ("keambar"); // defines a string stream that has been written to "keambar;

S> read data from string s

S <write characters to s;

Although sstream is simple, it is very practical and easy to use :)

<Iostream> most input/output operations can be used for stringstream.

/* = /*

# Inclde <fstream>

Ifstream read ("in.txt"); // open the in.txt file.
Ofstream write ("out.txt"); // open the out.txt file and create it if no out.txt file exists.

Read> // read from a file

Cout <// output to file

Read. close (); // close the file bound to read;

Read. open ("in2.txt"); // refresh and bind read_in2.txt;

Read. is_open () // return the bool value, indicating whether the file bound to s is nearly opened;

File mode (mod)S. open (file name, mod)

In is opened as read

Out is opened in write mode

Each write operation of the app locates at the end of the file.

Open ate and navigate to the end of the file

Trunc Truncation

Binary is enabled in binary mode.

By default, oftream is used to open the file in the out mode, and the file is truncated. to retain the original content, the app mode is required.

The following content is from the documentSeekg ()/seekp () and tellg ()/tellp ()

Seekg ()/seekp () and tellg ()/tellp ()

Input stream operations: seekg () and tellg ()

Operations on the output stream: seekp () and tellp ()

The following uses the input stream function as an example to describe its usage:

Seekg () is used to locate the input file. It has two parameters: the first parameter is the offset, and the second parameter is the base address.

For the first parameter, it can be a positive or negative value. Positive indicates backward offset, and negative indicates forward offset.

The second parameter can be:

Ios: beg: indicates the start position of the input stream.

Ios: cur: indicates the current position of the input stream

Ios: end: indicates the end position of the input stream.

The tellg () function does not require a parameter. It returns the position of the current positioning pointer, which also represents the size of the input stream.

Other operations

Peek ()// The peek function is used to read and return the next character, but does not extract the character to the input stream. That is to say, the character is still used as the next character to be extracted to the input stream.

For exampleHttp://www.cplusplus.com/reference/istream/istream/peek/Routine

// istream::peek example#include <iostream> // std::cin, std::cout#include <string> // std::stringint main () {std::cout << "Please, enter a number or a word: ";char c = std::cin.peek();if ( (c >= '0') && (c <= '9') ){              int n;std::cin >> n;std::cout << "You entered the number: " << n << '\n'; 15}else{std::string str;std::getline (std::cin, str);std::cout << "You entered the word: " << str << '\n';}return 0;}

Cin. read (char * buffer, streamsize num) // read by byte

Cin. write (const char * buffer, streamsize num) // output in bytes

For example

struct {       int height;int width;} rectangle;input_file.read ( (char *) (&rectangle), sizeof (rectangle) );if ( input_file.bad() ) {cerr << "Error reading data" << endl;exit ( 0 );}

/* = /*

# Inclde <iomanip>

When formatting output is involved, not only the <iomanip> header file is used, but also the <iostream>

<Iostream> has

Cout. fill (char ch) // set the padding character to ch

Cout. fill () // returns the current filled character

Cout. width (int k) // set the output width to k, which is only valid for the next output.

For example

 

cout << 32 << endl;cout.width (5);cout << 32 << endl;cout << 32 << endl;cout.fill ('#');cout.width (5);cout << 32 << endl;cout << cout.fill() << endl;

 

Output

32
32
32
### 32
#

Cout. flags ()// Return the int value, indicating the current format

Cout. precision (int k)// Retain the k-bit valid number. If no value is added, the int value is returned, indicating the current setting.

Cout. setf (ios ::)// Enable the flag format

Ios format

Boolalpha // outputs "true" or "false" based on the bool value ".

Dec // output in decimal format.

Hex // return an integer in hexadecimal notation.

Oct // an integer in octal format

Fixed // process the number of points in the normal fixed-point format (non-scientific Notation)

Internal // insert a required number of characters between the symbol bit and value to align the two ends of the string

Left // insert a character at the end of the string to align the string to the left

Right // insert a character before the string to align the string to the right

Scientific // calculate the number of vertices by scientific notation (with exponential domain)

Showbase // Add a prefix to the integer to indicate its hexadecimal prefix

Showpoint // forcibly insert the decimal point into the decimal point indicated by the floating point number (by default, the integer indicated by the floating point number does not display the decimal point)

Showpos // force + sign before a positive number

Skipws // ignore leading Spaces

Unitbuf // As described earlier, cache is cleared after each insert (output) operation.

Uppercase // force uppercase letters

FromHttp://www.cnblogs.com/devymex/archive/2010/09/06/1818754.html

For more operations, see

Each of the preceding formats occupies an independent digit. Therefore, you can use the "|" (bit or) Operator in combination. Call setf/unsetf or flags to set the format as follows:

cout.setf(ios::right | ios::hex); // Set the hexadecimal right alignment

cout.setf(ios::right, ios::adjustfield); // Cancel other alignment and set it to right alignment

Setf can accept one or two parameters. The version of a parameter is set to the specified format. In the versions of the two parameters, the latter parameter specifies the deletion format. The three defined combination formats are as follows:

  • Ios: adjustfield combined bits in alignment format
  • Ios: basefield in combination
  • Ios: floatfield combined bits of floating point representation

In addition

The cout. flag operation has the following usage:

Int number = 32; cout. setf (ios: showbase); // set to display base prefix // setw () function in <iomanip>, including using 

 

The output is

0x20 040
040
32
040

References: c ++ primer, c ++ Reference

 

 

 

 

 

 

 

 

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.