当前位置:网站首页>8 IO Library
8 IO Library
2022-06-12 06:49:00 【A building climbing pig】
8 IO library
8.1 IO class
1、 Most of IO Library tools :C++ Languages do not directly handle input and output , Instead, it is handled through a family of types defined in the standard library IO. These types support reading data from the device 、 Write data to the device 10 operation , The device can be a file 、 Console window, etc . There are also types that allow memory lO, namely , from string Reading data , towards string Write data . Most of the IO Library tools :
- istream ( Input stream ) type , Provide input operation .
- ostream ( Output stream ) type , Provide output operation .
- cin, One istream object , Read data from standard input .
- cout, One ostream object , Write data to standard output .
- cerr, One ostream object , Usually used to output program error messages , Write to standard error .
>>Operator , Used from a istream Object to read input data .<<Operator , Used to send a message to ostream Object write output data .- getline function ( See C++ primer The fifth edition 3.3.2 section , The first 78 page ), From a given istream Read a row of data , Deposit into a given string In the object .
2、 other IO type : To support these different kinds of IO Processing operations , stay istream and ostream outside , The standard library also defines some other IO type , Defined in three separate header files :iostream Defines the basic types of read and write streams ,fstream Defines the type of read-write named file ,sstream Read write memory is defined string Type of object .
- iostream The header file : Read and write data from the standard stream ,istream、ostream etc. , Summed up in DOS Read data between window and memory .
- fstream The header file : Read and write data from a file ,ifstream、ofstream etc. , Summed up in Read data between memory and file .
- sstream The header file : Read and write data from a string ,istringstream、ostringstream, That is to say Read character data between memory and memory .
3、IO The relationship between : The standard library allows us to ignore the differences between these different types of streams , This is through the inheritance mechanism (inheritance) Realized . Using templates ( See C++ primer The fifth edition 3.3 section , The first 87 page ), We can use classes with inheritance relationships , You don't have to understand how inheritance works T Details of . In short , The inheritance mechanism allows us to declare that a particular class inherits from another class . We can usually use a derived class ( Inheritance class ) Object as its base class ( Inherited classes ) Object to use . type ifstream and istringstream Inherit from istream. therefore , We can use it like istream Object to use ifstream and istringstream object . in other words , How do we use it cin Of , You can use these types of objects in the same way . for example , It's OK for one ifstream or istringstream Object call getline , You can also use >> From a ifstream or istringstream Object . Allied , type ofstream and ostringstream Inherit from ostream. therefore , How do we use it cout Of , You can use these types of objects in the same way .
4、IO Objects cannot be copied or assigned :IO Objects cannot exist in containers , Formal parameters and return types cannot be stream types , Formal parameters and return types are generally references to streams , Read and write a IO The object changes its state , So the references passed and returned cannot be const Of .
ofstream out1, out2;
out1 = out2;// error : Can't assign value to object
ofstream print(ofstream); // error : You cannot set a formal parameter or return type to a stream type
out2 = print(out2); // error : out2 Not a modifiable lvalue
5、 operation IO The condition state of : In the following table ,strm It's a kind of IO type ( Such as istream),s Is a stream object .
8.2 File input and output
The header file fstream Three types are defined to support files IO: ifstream Read data from a given file ,ofstream Write data to a given file , as well as fstream You can read and write to a given file . These types provide operations similar to cin and cout The operation is the same , It can be used IO Operator (<< and >>) To read and write files , It can be used getline From a ifstream Reading data .
8.2.1 Use FileStream objects
Except inherited from iostream In addition to the type of behavior ,fstream The types defined in also add - - Some new members to manage the files associated with the stream . These operations are listed in the following table , It can be done to fstream、ifstream and ofstream Object to invoke these operations , But not to others IO Type to invoke these operations .

8.2.2 File mode
Each stream has an associated file pattern (file mode), Used to indicate how to use files .

1、 File mode limitations :
- Only for ofstream or fstream Object settings out Pattern .
- Only for ifstream or fstream Object settings in Pattern .
- Only when out It can only be set when it is also set trunc Pattern .
- as long as trunc Not set , You can set app Pattern . stay app In mode , Even if you don't explicitly specify out Pattern , Files are always opened as output .
- By default , Even if we don't specify trunc, With out The file opened in mode will also be truncated . In order to keep out Contents of files opened in mode , We must also specify app Pattern , This will only append the data to the end of the file ; Or both in Pattern , That is, open the file and read and write at the same time
- ate and binary Patterns can be used for any type of FileStream object , And can be combined with any other file mode .
2、 The default mode for file streams : And ifstream The associated file defaults to in Mode on ; And ofstream The associated file defaults to out Mode on ; And fstream The associated file defaults to in and out Mode on .
3、 With out Opening a file in mode discards existing data : By default , When we open a ofstream when , The contents of the file will be discarded . Stop one ofstream The way to empty the contents of a given file is to specify app Pattern :
// In these statements ,filel Are truncated
ofstream out ("file1"); // Implicitly open the file in output mode and truncate the file
ofstream out2 ("file1", ofstream: :out); // Implicitly truncate files
ofstream out3("file1", ofstream: :outI ofstream: :trunc) ;
// In order to preserve the contents of the file , We must explicitly specify app Pattern
ofstream app("file2", ofstream: :app); // Implicit output mode
ofstream app2 ("file2", ofstream: :out | ofstream: :app) ;
4、 Every time you call open The file mode will be determined when : Every time you open a file , Set the file mode , It may be set explicitly , It can also be set implicitly . When the program does not specify a mode , Just use the default values .
8.3 string flow
sstream The header file defines three types to support memory I0, These types can be applied to string Write data , from string Reading data , It's like string It's a IO As flow .
istringstream from string Reading data ,ostringstream towards string Write data , And the header file stringstream Both from string You can also read data to string Writing data . And fstream Similar type , The header file sstream The types defined in are inherited from the types we have used iostream The header file
Type defined in . Except for inherited operations ,sstream The types defined in also add members to manage the string. The operations in the following table , It can be done to stringstream Object to invoke these operations , But not to others IO Type to invoke these operations .

8.3.1 Use istringstream
Example : Suppose there is a file , List some people and their phone numbers . Some people only have
A number , Others have more than one home phone 、 Work phone 、 Mobile phones, etc . Such as

#include<iostream>
#include<vector>
#include<sstream>
using namespace std;
struct PhoneList
{
string name;
vector<string> phonenum;
};
int main()
{
// phonestring Used to save phone numbers
// cinstring Is used to getline Data flow into istringstram, And the multiple data separated by spaces are all recorded
string phonestring,cinstring;
// Define a phone list
vector<PhoneList> phlist;
while(getline(cin,cinstring)){
// Define a phone table object , Save a phone list information
PhoneList phobj;
// from DOS Read in string object Cannot copy directly
// istringstream isobj = cinstring; The usage is wrong
istringstream isobj(cinstring);
// listone.name = isobj; The usage is wrong , The stream operator must be used
isobj>>phobj.name;
// according to getline Read in data , The first direct inflow name, The rest is a list of incoming deposit numbers separated by spaces
while(isobj>>phonestring){
phobj.phonenum.push_back(phonestring);
}
// Push this phone object into the phone list
phlist.push_back(phobj);
}
// Loop output object
for(auto p:phlist){
cout<<p.name<<" ";
for(auto n:p.phonenum){
cout<<n<<" ";
}
cout<<endl;
}
return 0;
}
Program last input zhangsan 123 11 22
lisi 11 22 11
wangwu 11
^Z With crtl+Z End input
The final output is the same as the previous input .

Program flow chart :

边栏推荐
- Tomato learning notes -vscade configuring makefile (using task.jason and launch.jason)
- LeetCode-219. Duplicate Element II present
- 六月集训 第七日 ——哈希表
- VSCode常用插件
- Dépannage de l'opération cl210openstack - chapitre expérience
- LeetCode-1716. Calculate the amount deducted from the bank
- LeetCode-419. Battleship on deck
- 应届生苦恼:是去华为拿1万多低薪,还是去互联网拿2万多高薪
- Leetcode: Sword finger offer 66 Build product array [application of pre and post infix]
- When SQL server2019 is installed, the next step cannot be performed. How to solve this problem?
猜你喜欢

数据库全量SQL分析与审计系统性能优化之旅

postman拼接替换参数循环调用接口

上传文件(post表单提交form-data)

SQL injection - blind injection

Tomato learning notes-stm32 SPI introduction and Tim synchronization

CL210OpenStack操作的故障排除--章節實驗
![Leetcode: Sword finger offer 63 Maximum profit of stock [record prefix minimum and or no brain segment tree]](/img/3a/3bba4fc11469b4cf31c38e35a81ac1.png)
Leetcode: Sword finger offer 63 Maximum profit of stock [record prefix minimum and or no brain segment tree]

初中学历,从不到3K,到月薪30K+,不设限的人生有多精彩

PHP一句话木马深度详细剖析

“我被大厂裁员了”
随机推荐
张驰课堂:2022年CAQ中质协六西格玛考试时间通知
Cron expression and website generation
MySQL group query to obtain the latest data date function of each group
企业微信官方 加解密库 PHP7版本报错 mcrypt_module_open 未定义方法 并且被PHP抛弃 解决方法使用 openssl解决
LeetCode-1189. Maximum number of balloons
PowerDesigner connects to entity database to generate physical model in reverse
leetcode:890. Find and replace mode [two dict records set]
platform driver
Torch models trained in higher versions report errors in lower versions
六月集训 第二天——字符串
LeetCode-219. Duplicate Element II present
5 statement
【图像去噪】基于偏微分方程(PDE)实现图像去噪附matlab代码
LeetCode-1873. Calculate special bonus
The second day of June training - string
Oracle Database
LeetCode-1185. Day of the week
六月集训 第一日——数组
leetcode 278. First wrong version
Leetcode: Sword finger offer 66 Build product array [application of pre and post infix]