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.

The use of CIN and cout is very simple, and we can extract the data from the user's keyboard input from CIN by extracting the (get-from) character ">>", which can be achieved from the keyboard to the program, or by inserting the (put-to) character "<<" Inserts data from the program into the cout to implement 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;     // Insert the number 1 into the cout object, which flows from the program to the screen cout<<"Hello world! " // Inserts the string "Hello world!" into the cout object cout<<""<<1+2;   // Inserts the string "1 + 2 =" into the cout object and evaluates the 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:

// variables for saving user input data string strName;  // a variable of type string that holds the string entered by the user int 0 // a variable of type int that holds the integer entered by the user // extracts the user-entered string data and integer data from the Cin object, // For example, enter "Liangqiao (space) 28 (carriage return)" // Cin reads both the "Liangqiao" and the "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 namespaceusing namespacestd;intMain () {//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 outputcout<<"Please enter two integers (e.g., for example):"<<Endl; //variables for saving input data    intN1, N2; //extracts two integers from the user input, with a space interval between integerscin>> N1 >>N2; //Processing of data//calculates the addend of two and saves the result to a nres variable    intNres = n1 +N2; //output two addend and calculation results to the screencout<< N1 <<" + "<< N2//two x addend<<" = "<< nres <<endl;//Calculation Results     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



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


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


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


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


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 header files required#include <fstream>using namespacestd;//Main functionintMain () {//defining variables, saving data in a program    intnyear, 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 pathIfstream Fin ("Date.txt"); //determine if the Date.txt file opened successfully//If the file is opened successfully, the contents are read from the file    if(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 3Fin>>nyear>>nmonth>>ndate; //display the Read data to the screencout<<"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 failscout<<"Unable to open file and read"<<Endl; }        //prompt the user to enter new data and write it to a filecout<<"Please enter a new date (for example, 1981 9):"<<Endl; //gets the data entered by the user through the keyboard and saves it to the appropriate variableCin>>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 theOfstream Fout ("Date.txt"); //If the Date.txt file is opened successfully, the data entered by the user is written to the file    if(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.//To facilitate future reading, the data output here is separated by a spacefout<<nyear<<" "<<nMonth<<" "<<ndate; //when the write is complete, close the fileFout.close (); }    Else    {        //Prompt for user information if the file cannot be openedcout<<"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:


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.

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

Related Article

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.