当前位置:网站首页>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 :

边栏推荐
- The seventh day of June training - hash table
- 六月集训 第八日——前缀和
- 美团获得小样本学习榜单FewCLUE第一!Prompt Learning+自训练实战
- android studio 利用数据库实现登录注册界面功能
- LeetCode-419. Battleship on deck
- 六月集训 第五天——双指针
- Are you still using like+% for MySQL fuzzy query?
- It only takes 10 minutes to understand the underlying principle of NiO
- esp32 hosted
- Troubleshooting of cl210openstack operation -- Chapter experiment
猜你喜欢

【数据聚类】本专栏中涉及数据集、可视化及注意事项

I met 15 people recently and found that I couldn't answer the basic question of this test

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

Node. Detailed installation tutorial of CPM and cnpm (including error resolution)

Troubleshooting of cl210openstack operation -- Chapter experiment

使用 ms17-010 永恒之蓝漏洞对 win7 进行渗透及建立永久后门

leetcode 704. Binary search

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

2 variables and basic types

Category 7
随机推荐
Use ms17-010 Eternal Blue vulnerability to infiltrate win7 and establish a permanent back door
2021 robocom world robot developer competition - undergraduate group (Preliminary)
Host computer development (firmware download software requirement analysis)
Descscheduler secondary scheduling makes kubernetes load more balanced
May training (day 28) - Dynamic Planning
C language pointer
CL210OpenStack操作的故障排除--章節實驗
2021 RoboCom 世界机器人开发者大赛-本科组(初赛)
I met 15 people recently and found that I couldn't answer the basic question of this test
android studio 利用数据库实现登录注册界面功能
platform driver
LeetCode-1350. Invalid students
【数据聚类】本专栏中涉及数据集、可视化及注意事项
Drawing grid navigation by opencv map reading
LeetCode-1490. Clone n-ary tree
leetcode:剑指 Offer 63. 股票的最大利润【记录前缀最小和 or 无脑线段树】
Computer composition and design work05 ——fifth verson
Install MySQL tutorial
使用 ms17-010 永恒之蓝漏洞对 win7 进行渗透及建立永久后门
上传文件(post表单提交form-data)