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

Source: Internet
Author: User
Tags rewind

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

After listening to the self-introduction of helloworld.exe, you know that the task of a C ++ program is to describe data and process data. The objects of these two tasks are data, but the problem is that data cannot be generated out of nothing, and C ++ programs cannot create data out of thin air. So where does the data in the C ++ program come from?

In the real world, exchanges between countries are completed by diplomats. In the C ++ world, there are also diplomats responsible for data exchange between applications and the outside world. Their names are basic input/output stream objects (iostream ). When a C ++ program is working, istream will input real-world data (for example, user input data from the keyboard) into the program, then the C ++ program can process the data. After the C ++ program obtains the result data, the output diplomat (ostream) will output the result data again (for example, output to the screen or file ). In the C ++ program, the flow of such data between the program and external objects (keyboard, screen, etc.) is called stream ), the two diplomats, istream and ostream, are responsible respectively. With the cooperation of the two diplomats, the C ++ program was completed to communicate with external data.

2.2.1 standard input and output objects

For ease of use, four basic input/output stream (I/O) objects have been pre-defined in the C ++ standard library, the most common is the cin object for keyboard input and the cout object for screen output. In addition, the standard library defines two auxiliary output objects: cerr used to output program error information and clog used to output log information. These objects have been pre-defined in the standard library. As long as the corresponding header file <iostream> is introduced, we can directly use them in the program to complete the basic input/output of the program, just as we directly use cout in the above program to output "Hello World!" to the screen!" The string is the same.

The use of cin and cout is very simple. We can extract the data input by the user through the keyboard from the cin by extracting the (get-from) character ">, implement data input from the keyboard to the program. You can also insert the data in the program to the cout by inserting the put-to character "<, implement data output from the program to the screen. Here, the direction of the arrow visually represents the direction of data flow. When data is input, the data flows out from the cin object to the program, so the arrow points to the direction away from the cin object. when the data is output, the data flows into the cout object from the program, so the arrow points to the direction near the cout object. For example, you can insert a number or string to the cout object using the "<" insert to display it on the screen:

Cout <1; // Insert the number 1 to the cout object. The data flows from the program to the cout <"Hello World! "; // Insert the string" Hello World! "to the cout object !" Cout <"1 + 2 =" <1 + 2; // Insert the string "1 + 2 =" and the calculation result of 1 + 2 to the cout object.

Insert the number "1" in the first sentence into the cout object, so that the number 1 is displayed on the screen. Similarly, the second sentence will display a string "Hello World!" on the screen !". In the last statement, the system first calculates the "1 + 2" result data 3, then, the first plug-in inserts the string "1 + 2 =" into the cout object, and the second plug-in inserts the calculated result data 3 into the cout object, the final output we see on the screen is a string like "1 + 2 = 3.

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

// String strName, the variable used to save user input data; // string type variable, used to save user input string int nAge = 0; // int type variable, used to save the user input integer // extract the user input string and integer data from the cin object, // For example, enter "Liangqiao (Space) 28 (Press ENTER) "// cin reads the" Liangqiao "and" 28 "data, // stores the data in the strName and nAge variables respectively. cin> strName> nAge;

Here, we first define two variables: strName and nAge, which are used to save the string data and integer data entered by the user respectively. Then, extract the data input by the user through the keyboard from the cin object using the extract character ">". When the program is executed here, it will be paused and waiting for user input, after the user completes the input and press enter, ">" extracts user input data from the cin object and saves the data to the corresponding variables respectively, this completes the data input from the keyboard to the application.

Next, let's take a look at an instance used in combination with input and output.

// Introduce the header file that defines the input/output stream object # include <iostream> // use the std namespace using namespace std; int main () {// output prompt information on the screen // After the string, we also output a special operator endl, // It is used to indicate the end of line. It will make the output line break // and refresh the output buffer, let the user immediately see the output cout <"enter two integers (for example, 19 83):" <endl; // The int n1, n2 variables used to save the input data; // extract the two integers entered by the user from cin. When the input is made, the integers are separated by spaces (cin> n1> n2; // process the data // calculate the sum of the two integers and save the result to the nRes variable int nRes = n1 + n2; // output the two Addons and computing results to the cout <n1 <"+" <n2 // two Addons <"=" <nRes <endl; // return 0 ;}

Using cin and cout, just a few lines of code, we realized an integer addition computing program. It can accept the data input by the user (two integers), then process (ADD and calculate) the data, and finally output the result data (nRes, the problem (the sum of the two integers is calculated) is successfully solved.

2.2.2 output format Control

When outputting data, in addition to simply outputting data, we often have different requirements for data output formats in different application scenarios. For example, the output is a decimal of the double type. If this decimal point is only a student's score, it is enough to retain a decimal point in the output, and if it is a Renminbi exchange rate, the output must retain at least three decimal places. To control the output format, C ++ provides many operators. For example, the endl we used in the previous code is a operator that controls the line feed. These operators can be directly inserted into the output stream object cout using "<" to control the output format. Most of these operators are defined in the header file <iomanip>. If you want to use them in the code to control the output format, you must first use the pre-compiled command # include to introduce this header file. Table 2-1 lists common format operators in C ++.

Table 2-1 common output stream format Operators

Operator

For use

Dec

Displays numeric data in decimal format. This is the default setting of the output stream object.

Hex

The value data is displayed in hexadecimal notation. For example, a decimal value of 54321 is output to d431 in hexadecimal notation. If a showbase operator is inserted into the output stream at the same time, you can also output the 0x prefix of the hexadecimal value.

Oct

The value data is displayed in octal notation, and the same decimal value is 54321. In this mode, the output value is 152061 of octal notation.

Endl

Insert line breaks and refresh the output stream buffer

Setprecision (n)

Set the output precision of a floating point to n. By default, the precision refers to the number of all digits before and after the decimal point in the floating point number. If the fixed operator is inserted into the output stream at the same time, the precision is the number of digits after the decimal point.

Setw (n)

Set the display width of each output data

These operators can meet some special output format requirements. For example, to output a decimal point of 1.23456 in the format of "retain two valid digits after decimal point", and then wrap the line, you can use the following code:

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

Here, a fixed operator is first inserted into the cout object to output the decimal number with a fixed number of decimal places. Then, use setprecision () to set the number of valid digits after the decimal point to be retained, so that the output format of "retain two valid digits after the decimal point" can be met.

In addition to the control of the output format of numeric data, we also need to control the output format of the string in many cases to make the output of the program more beautiful. Similar to the output format in which the insert operator controls numeric data in the output stream, we can also control the output format of a string by adding some escape characters for format control. Here, the so-called escape character is a special character consisting of "\" before some characters, which no longer expresses its original meaning, in turn, it expresses the control of the format or other special meanings, so it is called an escape character. Common Format control escape characters include "\ n", which indicates line breaks, and "\ t", which indicates the distance output of tabs separated by integers. For example, the following code implements line feed display:

Cout <"multiple lines \ n show a string" <endl;

After the program is executed, "\ n" is displayed on the screen, dividing a string into two lines for display:

Split multiple rows

Display a string

Using these output stream operators and escape characters in the C ++ language, you can flexibly customize and format the output to meet the Personalized Requirements of the output format.

2.2.3 read/write files

In addition to 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 files: reads data from a file to an application for processing, which enables data input. writes the processed result data to a file for storage and outputs data. The C ++ Standard Library provides ifstream (input file stream) and ofstream (output file stream), which are used to read data from the file and write data into the file respectively. They are defined in the <fstream> header file. If you want to use them in a program to read and write files, you need to first introduce this header file. (It should be noted that this section involves a lot of high-level content in C ++, such as classes, objects, and member functions. If it is difficult to read this section, you can skip this section and read it after you have mastered the necessary knowledge .)

In use, we first need to create their instance objects. If you want to output data to a file, you can create an ofstream object. Otherwise, you can create an ifstream object. By providing a file name when creating an object, these objects can be opened or created to associate the object with a specific file, and then these objects can be operated, determine whether the file is successfully opened.

After you prepare these created objects to open the file, you can directly read and write the file through these objects. This method is similar to using cin or cout for data input/output. We also use the insert operator "<" to insert data into an ofstream object, output the data in the program to the file associated with this object. extract data from an ifstream object with the extract Letter ">, input data from the file associated with this object to the program. For example, we first read the content in a file and then write the new content into the file:

# Include <iostream>

# Include <iostream> // introduce the file input/output header file # include <fstream> using namespace std; // The main function int main () {// defines the variable, save the data int nYear, nMonth, nDate in the program; // create the input file stream object final, and try to open the data.txt file // This file should be located in the same directory of the exe file, // you can directly open it with the file name, otherwise, you should use the complete file path ifstream fin ("Date.txt"); // determine whether the file is successfully opened. // if the file is successfully opened, read the content from the file if (fin. is_open () {// use the extract character ">" to read data from the file input stream object fin, the content saved to the corresponding variable // file should be three integers separated by spaces, for example, 1983 7 3 fin> nYear> nMonth> nDate; // display the read data to the cout <"the date recorded in the file is" <nYear <"-" <nMonth <"-" <nDate <<endl; // close the file fin. close () ;}else {// if the file fails to be opened, the system prompts the error code cout <"unable to open the file and read" <endl ;} // prompt the user to enter new data and write it to the file cout <"enter a new date (for example, 1981 9 22):" <endl; // obtain the data input by the user through the keyboard and save it to the corresponding variable. cin> nYear> nMonth> nDate; // create the output file flow object foutand try to open the data.txt file. // if the file does not exist, create a new file and open ofstream fout ("Date.txt"); // if the Date.txt file is successfully opened, write user input data to the file if (fout. is_open () {// insert data into the file output stream object fout using the "<" plug-in, // also writes data into the associated data.txt file. // for future reading convenience, the output data here uses spaces as the interval fout <nYear <"" <nMonth <"" <nDate; // after the data is written, close the file fout. close () ;}else {// if the file cannot be opened, the system prompts the user information cout <"unable to open the file and write" <endl ;}return 0 ;}

In this program, a final object of the input file ifstreamis created first, and the corresponding structure is used to associate it with a local file date.txt. The so-called constructor is the function executed when this object is created. In this case, the file name "date.txt" is used as the parameter of the constructor. In fact, this file is opened and used to create a fin object. In addition, you can use the open () member function provided by fin to open a file. After we create a fin object, before reading the object, we often need to use its is_open () member function to determine whether the file is successfully opened to improve the robustness of the program, the next read operation can be performed only when the file is successfully opened. After you use fin to open a file, you can extract various types of data from the final file using the ">" marker ", and read the data from the data.txt file on the marker. For example, if the content in the file is as follows:

1982 10 3

The code used in the program is:

fin>>nYear>>nMonth>>nDate;

By default, the separator ">" reads data from the file one by one and saves it to the corresponding data variables. After the code is executed, the values 1983, 7, and 3 in the file are read and saved to the nYear, nMonth, and nDate variables in the program, implements data input from files to programs. After reading the file, you must use the close () member function to close the file.

Similarly, to write data to a file, you need to create an object fout of the output file stream ofstream and open a file through its constructor or open () function, associate the file with the fout object, and insert the data to be output to the fout object through the "<" symbol, which is equivalent to writing the data to the associated file, after the output is complete, use the close () function to close the file, so that the data output from the program to the file is realized. The entire process is 2-9.

Figure 2-9 file read/write

Here we only introduce the most basic operations of file input/output, but it can basically meet our daily needs. In addition, C ++ provides richer file read/write operations, such as reading/writing binary files and adjusting mobile read/write locations, this satisfies our further needs for reading/writing files.


C language reads data from files, sorts the data, and outputs the data to the screen.

# Include "stdio. h"
Int main ()
{
Int n, cnt = 0, I;
Char s [100];
Freopen ("D: \ a.txt", "r", stdin );
While (scanf ("% d", & n )! = EOF)
{
Printf ("% d", n );
Scanf ("% s", s );
Cnt = 0;
For (I = 0; s [I]; I ++)
Cnt + = (s [I] = 'A ');
Printf ("% d a \ n", cnt );
}
Return 0;
}

How to use C language to write part of the data into a file first, and then read and output the data on the screen

Change fopen () to: if (fp = fopen ("1s.txt", "w +") = NULL)
Fputc (p, fp); changed to: fprintf (fp, "% d", p );
Before reading the statement, add a file to wrap it back to the file header: rewind (fp );
----------------
Int main (){
FILE * fp;
Char read [1000];
Char s;
Long p;
If (fp = fopen ("1s.txt", "w +") = NULL)
{
Printf ("\ nOpen file error! Press any key exit! ");
Getchar ();
Exit (0 );}
P = 123456;
S = '\ n ';
Fprintf (fp, "% d", p );
Fputc (s, fp );
Fprintf (fp, "% d", p );
Rewind (fp );
Fgets (read, 1000, fp );
Printf ("% s", read );
System ("pause ");
Return 0 ;}

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.