Hello, C + + (5) How to output data to the screen, input data from the screen and read and write files?

Source: Internet
Author: User

2.2 Basic input/output streams

After listening to HelloWorld.exe's self-introduction, you already know that the task of a C + + program is to describe the data and process the data. The object of both tasks is data, but the problem is that the data can not be generated out of nowhere, C + + programs can not create data in thin air. So where does the data in the C + + program come from?

In the real world, communication between nations is done through diplomats. In the C + + world, there are also diplomats responsible for data exchange between applications and the outside, whose names are basic input/output stream objects (iostream). When a C + + program is working, the input diplomats (IStream) input the real-world data (for example, user input data from the keyboard) into the program, and the C + + program can then process the data. When the C + + program obtains the result data, the diplomat responsible for the output (ostream) outputs the resulting data (for example, output to a screen or file). In C + + programs, we refer to the flow of this data between programs and external objects (keyboards, screens, etc.), which are the responsibility of two diplomats, IStream and ostream, respectively. It was the two diplomats who cooperated to complete the exchange of data between C + + programs and the outside world.

2.2.1 Standard input and output objects

For ease of use, 4 of the most basic input/output stream (I/O) objects have been pre-defined in the C + + standard library, the most common of which is the Cin object responsible for keyboard input and the Cout object responsible for screen output. In addition, the standard library defines two auxiliary output objects, the Cerr used for outputting program error messages and the clog for outputting log information. These objects have been pre-defined in the standard library, as long as the corresponding header file <iostream>, we can use them directly in the program to complete the basic input/output of the program, as we in the above program directly using cout to the screen output "Hello world! "As a string.

cin and cout are very simple to use, we can extract (Get-from) the ">>" from CIN to extract the data entered by the user through the keyboard to achieve the data input from the keyboard to the program, or by inserting (put-to) character " << "Inserts data from the program into the cout to achieve data output from the program to the screen. Here, the direction of the arrows graphically represents the direction of the data flow. When the data is entered, the data is streamed out from the CIN object to the program, so the arrows point in the direction away from the Cin object, and when the data is output, the data flows from the program into the Cout object, so the arrows point toward the direction near the Cout object. For example, you can use the "<<" caret to insert a number or a string into a cout object to display it on the screen:

cout<<1;     // to insert the number 1 into the cout object, this data flows from the program to the screen cout<<"Hello world!  Inserts the string "Hello world!" into the cout object cout<<"" <<1+// Insert string "1 + 2 =" into cout object and calculate result of 1+2     

The caret in the first sentence inserts the number "1" into the Cout object, which displays the number 1 on the screen. Similarly, the second sentence displays a string "Hello world!" on the screen ”。 And in the last statement, the system will first calculate the result of "1+2" Data 3, and then the first insert Inode "1 + 2 =" This string data into the Cout object, and then the second caret will be the result data 3 inserted cout object, so that the final output we see on the screen is " 1 + 2 = 3 "Such a string.

For the input stream object cin, you can use the extract ">>" from the cin input stream to get the data entered by the user through the keyboard and save it in a variable within the program. For example:

variable string strName for saving user input data ;  A variable of type string//string, used to hold the user input of a variable of type A/  / int, used to hold the user input integer // Extract the user input string data and integer data from the Cin object,// For example, enter "Liangqiao (space) 28 (carriage return)"// cin reads both "Liangqiao" and "28" data,//  and are saved to both StrName and NAge, respectively cin>>strname>>nage;           

Here, we first defined two variables strname and nage, respectively, to hold the user input string data and integer data. Then, using the extract ">>" from the Cin object to extract the data entered by the user through the keyboard, when the program executes here will pause to wait for user input, once the user completes the input and returns, ">>" The data entered by the user is extracted from the CIN object and stored separately in the corresponding variable, thus completing the input of the data from the keyboard to the application.

Here's a look at an example of input and output mates.

//Introduction of header files defining input/output Stream objects # include <iostream>//Using the STD namespaceUsingNamespaceStdIntMain () {//Output a hint on the screen//After the string, we also output a special operator, Endl,//It's used to indicate the end of a line (end of line), which causes the output to wrap//and refreshes the output buffer, allowing the user to immediately see the output cout<<"Please enter two integers (for example, 19 83):"<<Endl//Variables for saving input dataIntN1, N2;//Extracting two integers from CIN for user input, with spaces spaced between integers cin>> N1 >>N2;// Data processing // calculation two addend and, save the result to nres variable int nres = n1 + n2; // output two addend and calculation results to screen cout<< N1 << " + " << n2 // two addend << "  = "<< nres <<endl; // calculation result return 0;}             

Using CIN and cout, just a few lines of code, the implementation of an integer addition calculation program. It accepts data entered by the user (two addend), then processes (adds and computes) the data, and eventually outputs the resulting data (nres), making the problem (counting two integers) a satisfactory solution.

2.2.2 Output Format Control

When outputting data, in addition to simply outputting data, in different scenarios, we often have different requirements for the format of the data output. For example, the same is the output of a double type of decimal, if the decimal number is only a student score, then the output is sufficient to retain a decimal, and if it is a renminbi exchange rate, then the output should be kept at least three decimal places. In order to control the output format, C + + provides a number of operators, such as our previous code used in the Endl is a control of line-wrapping operators. These operators can be inserted directly into the output stream object cout using "<<" to achieve control of the output format. Most of these operators are defined in the header file <iomanip>, so if you want to use them in your code to control the output format, we need to first use the precompiled Directive # # to introduce this header file. Table 2-1 lists the commonly used format operators in C + +.

Table 2-1 Common output stream format operators

Manipulation characters

Role

Dec

Displays numeric data in decimal, which is the default setting for the output stream object

Hex

Numeric data is displayed in hexadecimal, for example, a decimal value of 54321 is displayed as a 16-d431 in the output. If you insert a showbase operator in the output stream at the same time, you can also output the 0x prefix of the hexadecimal value

Oct

Use octal to display the value data, the same decimal value 54321, in this mode will be output displayed as eight binary 152061

Endl

Insert line break and flush output stream buffer

Setprecision (N)

Sets the output precision of the floating-point number to N. By default, precision refers to the number of all numbers before and after the decimal point of a float. If the fixed operator is inserted in the output stream at the same time, then the precision refers to the number of digits after the decimal point

SETW (N)

Set the display width of each data for the output

These operators can be used in combination to meet some special output format requirements. For example, it is required to output decimal 1.23456 in the format "preserve two digits after the decimal point," and then wrap it in the following code:

cout<<fixed<<setprecision (2) <<1.23456<<endl;  

Here, you first insert a fixed operator to the Cout object, which indicates that the decimal value is output with a fixed number of decimal places. Then, with Setprecision () set the number of significant digits that need to be retained for the decimal point, so that you can reach the output format requirement of two significant digits after the decimal point is retained.

In addition to the control of the output format of the numeric data, many times, we also need to control the output format of the string, so that the output of the program is more beautiful. Similar to the output format for inserting operators in the output stream to control numeric data, we can also control the string output format by adding some escape characters for formatting control in the string. The so-called escape character is a special character that is preceded by some characters with a "\" symbol, which no longer expresses its original meaning, but instead expresses control of the format or other special meaning, so it is called an escape character. The commonly used format control escape characters are: "\ n" for line breaks, "\ t" for distance output for the entire number of tabs, and so on. For example, the following code implements a newline display:

cout<<" \ n Display a string " <<endl;  

After the program executes, you will see "\ n" on the screen dividing a string into two lines:

Split Multiple lines

Displays a string

The combination of these output stream operators and the format control escape characters provided by the C + + language enables flexible and versatile custom formatted output to meet the personalization requirements for the output format.

2.2.3 Read/write files

In addition to using hardware devices (keyboards, screens, etc.) and programs for input/output, more often, the program also needs to read and write files to achieve data input/output with the file: from the file read data to the application for processing, to achieve data input, the processing results of data written to the file to save, to achieve data output. The C + + standard library provides ifstream (input file stream) and Ofstream (output file stream), which are used to read data from a file and write data to a file, respectively. They are defined in the <fstream> header file, and if you want to use them in your program to read and write files, we need to introduce this header file first. (To be reminded, this section involves a lot of higher-order content in C + +, such as classes, objects, and member functions.) If you have difficulty reading this section, you can skip this section and wait until you have the necessary knowledge behind to read it, and you can easily understand it. )

When used, we first need to create their instance objects. If you are exporting data to a file, create an Ofstream object, and vice versa, create an Ifstream object. By providing a file name when creating an object, these objects can open or create the corresponding file, thereby associating the object with a specific file, then manipulating the object to determine whether the file opened successfully or not.

After you have completed the preparation of these open files for creating objects, you can read and write files directly from these objects. This is similar to the data input/output via CIN or cout, and we also use the caret "<<" to insert the data into a Ofstream object, implementing the output of the data in the program to the file associated with the object, with the extract ">>" Extracts data from a Ifstream object, implementing input data into the program from the file associated with the object. For example, we first read the contents of a file and then write the new content to the file:

#include <iostream>

#include <iostream>//Introduction of file input/output required header file # include <fstream>UsingNamespaceStd//Main functionIntMain () {//Defining variables, saving data in a programIntNyear, Nmonth, ndate;//Create the input file stream object fin and try to open the Data.txt file//This file should be located in the same directory as the EXE file.//To open directly with the file name, or you should use the full path ifstream fin ("Date.txt");//Determine if the Date.txt file opened successfully//If the file is opened successfully, the contents are read from the fileIf(Fin.is_open ()) {//Use the extract ">>" to read the data from the file input stream object fin and save it to the appropriate variable//The contents of the file should be three integers with a space interval, for example: 1983 7 3 Fin>>nyear>>nmonth>>Ndate;//Display the read data to the screen cout<<"The date recorded in the file is"<<nYear<<"-"<<nMonth<<"-"<<nDate<<Endl//When the read is complete, close the fileFin.close (); }Else{//Prompt for error message if File open fails cout<<"Unable to open file and read"<<Endl }//Prompts the user to enter new data and write it to the file cout<<"Please enter a new date (for example, 1981 9 22):"<<Endl//Gets the data entered by the user via the keyboard and saves it to the corresponding variable cin>>nyear>>nmonth>>Ndate;//Create the output file stream object Fout, and try to open the Data.txt file,//If the file does not exist, create a new file and open the Ofstream fout ("Date.txt");//If the Date.txt file is opened successfully, the data entered by the user is written to the fileIf(Fout.is_open ()) {//Insert data into the file output stream object Fout using the caret "<<",//That is, the data is written to the Data.txt file associated with it.// "" <<nMonth<<  " <<ndate; //else {// If the file cannot be opened, the user is prompted for information Cout<< Unable to open file and write  "<<ENDL;} return 0    

In this program, you first create an object fin for the input file stream ifstream, and use its constructor to associate it to a text file Date.txt. The so-called constructor is the function that the object executes when it is created. Here, the "Date.txt" file name is used as the constructor parameter, which is actually to open the file and use this file to create the Fin object. In addition, you can open a file by using the open () member function provided by Fin. After we create the Fin object, before the read operation, in order to improve the robustness of the program, we often need to use its is_open () member function to determine whether to open the file successfully, only the file is successfully opened for the next read operation. When a file is successfully opened with FIN, the extract ">>" can be used to extract a variety of data from fin, in effect reading the data from the Data.txt file. For example, if the contents of the file are as follows:

1982 10 3

The code to be read in the program is:

fin>>nyear>>nmonth>>ndate;

By default, the extract ">>" reads the data from the file and saves it to the appropriate data variable, separated by a space delimiter. After the execution of the code, the three values of "1983", "7" and "3" in the file are read and saved into the three variables of nyear, Nmonth and Ndate in the program, and the data input from file to program is realized. After the file has been read, you need to close the file with the close () member function.

Similarly, in order to write data to a file, you need to create an output file stream Ofstream object Fout, with its constructor or the open () function to open a file, associate the file with the Fout object, and then use the caret "<<" Inserting the data that needs to be output into the Fout object is equivalent to writing the data to the file associated with it, closing the file with the close () function after the output is complete, thus implementing the data output from the program to the file. The entire procedure is shown in 2-9.

Figure 2-9 File read/write

What we're going to introduce here is just the basics of file input/output, but it's basically enough to meet our daily needs. In addition, C + + also provides richer file read and write operations, such as read/write binary files, adjust the mobile read and write location, and thus also meet our further requirements for file read/write.

Original address: http://www.cnblogs.com/nihaoCPP/p/3955243.html

Hello, C + + (5) How to output data to the screen, input data from the screen and read and write files?

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.