2 basic input / output stream (iostream)

Keywords: C++ Back-end

Standard input and output objects

The iostream class library defines four basic input / output objects
cin: standard input, i.e. keyboard input
cout: standard output, i.e. screen output
cerr: handles standard errors, typically used to generate warning or error messages
clog: generates the execution information of the program
< < inserter, > > extractor
cout screen output

cout<<1;        // Inserts the value 1 into the output object
 cout<<"Hello World!";    // Insert the string "Hello World!" into the output object
 cout<<"1 + 2 = "<<1+2;   // Insert the string "1 + 2 =" and the calculation result of 1 + 2 into the output object
use cin Extract keyboard input
// Define two variables to hold user input data
int nAge; 
string strName; // Extracting integer data and string data input by the user from the input object cin,
// cin extracts the information entered by the user and saves it to the nAge and strName variables respectively

Examples of use of input with output:

#include "stdafx.h" / / the header file defining the I / O stream object is introduced
#Include < iostream > / / introduce std namespace
using namespace std; 
int _tmain(int argc, _TCHAR* argv[])
 // Output prompt information on the screen    
cout<< "Please enter two integers:" <<endl;     
int v1, v2;     // Extracts the integer entered by the user from the input object    
cin>> v1 >> v2;     // Output the calculation results to the screen    
cout<< "Two integers" << v1 << "and" << v2 << "Yes and yes" << v1 + v2 <<endl;     
return 0; 

Operation results

Where endl is the operator, the line feed is output, and the output buffer is refreshed to ensure that the user immediately sees the information that has been inserted into the output stream.

Output format control

In order to control the output stream format, C + + provides many manipulators. These manipulators can be directly inserted into the output stream to control the output format. They are defined in the header file iomanip. To use these manipulators, you need to use the precompiled instruction #include to introduce the header file.
Common output stream format manipulators:

decNumeric data is represented in decimal system
hexNumerical data is represented in hexadecimal
octUse octal to represent numerical data
endlInsert a newline character and brush a new stream
setprecision(int)Sets the precision of floating-point numbers. Precision is the number of all decimal numbers in floating-point numbers, including before and after the decimal point
setw(int)Sets the interval width between two data displays in the output stream
setioflagsThe default alignment of the output stream is text right alignment. The alignment can be reset by using the setiosflags and resetiosflags operators in the program

Example 1: it is required to display the floating point number 1.23456, two significant digits after the decimal point, and then wrap the line. You can use the following statement cout < < fixed < < setprecision (2) < < 1.23456 < < endl;
First, insert a fixed operator into cout object and let it output floating-point numbers in ordinary decimal counting method, otherwise it will output floating-point numbers in scientific counting method; Then, set the number of significant digits to be reserved through setprecision(), so as to meet the requirements of output format.
Example 2: control string format
Format control escape character: "\ n" indicates line feed; "\ t" indicates the distance of one Tab apart
Line feed display: cout < < split into multiple lines \ ndisplay a string < < endl

Read / write file

Header file definition: ofstream and ifstream data output and input

#include "stdafx.h" 
#include <iostream> 
// The header file required to import the input / output file stream object
#include <fstream> 

using namespace std;
// Main function
int _tmain(int argc, _TCHAR* argv[])
	int nYear, nMonth, nDate;	            // Define variables and save the data in the program
	ifstream fin("Date.txt");               // Try opening the Date.txt file and connecting it to the input file stream fin 
	if (!fin.bad())                         // If the Date.txt file is successfully opened, the contents are read from the file 
		fin.ignore(256, '\n');              // Ignore the prompt on line 1 in the file  
		fin >> nYear >> nMonth >> nDate;	// Use the extractor "> >" to read the recorded data from the file input stream fin and save it to the corresponding variable         
		cout << "The date in the file is" << nYear << "-" << nMonth << "-" << nDate << endl;	// Display data to screen  
		cout << "Unable to open file and read it" << endl;
	cout<<"Please enter the current date (mm / DD / yyyy):"<<endl;    // Prompt the user to enter new data and write it to the file 
	cin>>nYear>>nMonth>>nDate;     // Get the user's keyboard input from the user screen and save it to the corresponding variable    
	ofstream fout("Date.txt");	   // Try opening the file Date.txt and connecting it to the output file stream fout         
	if (!fout.bad())               // If the Date.txt file is successfully opened, the data entered by the user is written to the file
	{// Use the caret "< <" to write data to the file output stream fout, that is, write data to the file        
		fout<<"The current date entered by the user is:\n" 
			<<nYear<<" "<<nMonth<<" "<<nDate;       //Content written    
		fout.close();  // When writing is complete, close the file   
	{         // If the file cannot be opened, the user will be prompted for information        
		cout<<"Unable to open file and write"<<endl;    
	return 0; 



fin.ignore(256, '\n'); // Ignore the prompt on line 1 in the file. By default, fin is always read from the beginning of the file. In order to directly read the content of line 2, you can use "fin. Ignore (256, '\ n');" to ignore the content of line 1 and jump the reading position to line 2. Then, the three data separated by spaces in line 2 are extracted and saved into three variables through the extractor "> >"


To write data to a file, create an object fout of the output file stream, then open a file through its constructor or open() function, and insert the data into the fout object with the caret * * < < * * character

In addition to the above reading and writing, fstream provided by C + + can also read / write binary files, and even redefine "<" and "> >", so as to realize special reading / writing operations.

Posted by corillo181 on Mon, 01 Nov 2021 02:24:56 -0700