字符串类和标准输入输出流类专题讲座.doc_第1页
字符串类和标准输入输出流类专题讲座.doc_第2页
字符串类和标准输入输出流类专题讲座.doc_第3页
字符串类和标准输入输出流类专题讲座.doc_第4页
字符串类和标准输入输出流类专题讲座.doc_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

标准模板库STL字符串类和标准输入输出流类简介一、 C+中的字符串string1、 string是模板类basic_string的char型版本或者说模板类basic_string的实例化。 namespace std template class charT, class traits = char_traits, class Allocator = allocator class basic_string;namespace std typedef basic_string string;typedef basic_string wstring;2、 string 的成员函数Operation Effect constructors Create or copy a stringdestructor Destroys a string=, assign() Assign a new valueswap() Swaps values between two strings+=, append(), push_back() Append charactersinsert() Inserts characterserase() Deletes charactersclear() Removes all characters (makes it empty)resize() Changes the number of characters (deletes or appends characters at the end)replace() Replaces characters+ Concatenates strings=, !=, , , =, compare() Compare stringssize(), length() Return the number of charactersmax_size() Returns the maximum possible number of charactersempty() Returns whether the string is emptycapacity() Returns the number of characters that can held without be reallocation , at() Access a character, getline() Read the value from a stream Writes the value to a streamcopy() Copies or writes the contents to a C-stringc_str() Returns the value as C-stringdata() Returns the value as character arraysubstr() Returns a certain substringfind functions Search for a certain substring or character(有多种不同形式的查找,故有多个查找函数)begin(), end() Provide normal iterator supportrbegin(), rend() Provide reverse iterator support注:string的许多成员函数都有许多不同的版本(即参数的个数、类型有差别)。如构造函数string就有如下多种:string s Creates the empty string s string s(str) Creates a string as a copy of the existing string str string s (str, stridx) Creates a string s that is initialized by the characters of string str starting with index stridx string s(str, stridx, strlen) Creates a string s that is initialized by, at most, strlen characters of string str starting with index stridx string s(cstr) Creates a string s that is initialized by the C-string cstr string s (chars, chars_len) Creates a string s that is initialized by chars_len characters of the character array chars string s(num,c) Creates a string that has num occurrences of character c string s (beg, end) Creates a string that is initialized by all characters of the range beg, end) s.string() Destroys all characters and frees the memory又如其insert()成员函数亦有多种(详见The C+ Standard Library中&11.3 String Class in Detail)。3、 在string内定义的某些类型在string内部为应用的方便定义了许多类型,常用的有:string:size_type无符号整数,用来指定大小值和索引string:iterator迭代器string:npos表示未找到,初始值为-14、 字符数组、c_string、string和CString之间的相互转换 C+标准将c_string(C风格的字符串)的类型由char*改为了const char*。 C+标准规定了一个颇有争议的隐式转换,可以从const char*隐式转换为char* C+中存在从c_string到string的自动转换,反之却无。在windows程序设计过程中,经常会遇到要在字符数组、c_string、std:string和MFC中的CString类之间进行类型转换的情况。 字符数组就是由字符组成的数组。 C风格的字符串就是由字符组成的数组在其后加上一个0,与其相关的函数声明在string.h中。 C+模板库中的string是模板类basic_string的char型版本或者说实例化。此类的相关函数声明在string中。 MFC中的CString则是windows中常用到一种字符串形式,它间接派生自MFC的基类CObject,这使得它可以很方便的串行化(serialize)。各种转换的方法如下图所示:/例5-01 反转输入的每一个单词例程,如输入为I saw a reed.时输出为I was a deer.#include #include using namespace std;int main (int argc, char* argv) const string delims( t,.;); string line; while (getline(cin,line) if(line=exit)return 0; string:size_type begIdx, endIdx; begIdx = line.find_first_not_of(delims); /查找第一个不属于delims中字符的字符 while (begIdx != string:npos) endIdx = line.find_first_of (delims, begIdx); if (endIdx = string:npos) endIdx = line.length(); for (int i=endIdx-1; i=static_cast(begIdx); -i)cout linei; cout ; begIdx = line.find_first_not_of (delims, endIdx); cout endl; return 1;5、 示例/例5-2 回文数的计算#include #include using namespace std;void main()/本程序将11-10000中的回文数(即正向读和逆向读都一样的文本如12321、5555、/11611)打印到C:test.txt文件中ofstream outfile(C:test.txt);/新建一个文本文件C:test.txtchar buffer20;for(int i=11;i10000;i+)_itoa( i, buffer, 10 );/将i按10进制转换成字符数组放入bufferstring s1=string(buffer),s2(s1);/以字符数组buffer初始化字符串s1和s2/使字符串s2等于s1的颠倒数string:iterator begin=s1.begin(),end=s2.end()-1;while(begin!=s1.end()*end=*begin;-end;+begin;if(s1=s2)outfileiendl;/如果两者相等则输出system(edit c:test.txt);/在Dos下的编辑器中打开文件二、 C+中的标准输入输出流类1、 C+支持两种I/O系统:C语言的I/O系统和C+的面向对象的输入输出流类支持的I/O系统。2、 流的概念流是对数据传递过程的抽象,一个流中流动的: 如果是字符,则它是一个字符流; 如果是字符串,则它是一个字符串流; 如果是int,则它是一个int流; 如果是水,则它是水流(河流)。3、 基本流类C+中的基本输入输出流类是一套模板类,在这些模板类的基础上则衍生出许多char型的流类,如ios/wios、istream、ostream和iostream等,如:namespace std typedef basic_ios ios;typedef basic_ios wios;typedef basic_istream istream;typedef basic_istream wistream;typedef basic_ostream ostream;typedef basic_ostream wostream;typedef basic_iostream iostream;typedef basic_iostream wiostream; 它们之间的关系如图所示:其中:The base class ios_base defines the properties of all stream classes independent of the character type and the corresponding character traits. Most of this class consists of components and functions for state and format flags.4、 MS输入输出流类VC6中包括多种形式的支持输入输出的函数或类: C run-time library direct, unbuffered I/O ANSI C run-time library stream I/O Console and port direct I/O The Microsoft Foundation Class Library The Microsoft iostream Class Library其中包括两个C+输入输出流类,一个是C+创始人所作,一个是C+标准流类库,具体如下图所示:5、 学习输入输出流类从ios类开始(详细内容参考MSDN中Visual C+ DocumentationReferenceC/C+ Languages and Librariesiostream Class Library Referenceiosios)注:ios的成员包括从ios_base类继承而来的成员,以下不区分。a、 ios的数据成员 basefield记录当前进制(dec, oct, or hex)如:extern ostream os;if( ( os.flags( ) & ios:basefield ) = ios:hex ) . adjustfield记录当前填写方式(居左、居中、居右)如:extern ostream os;if( ( os.flags() & ios:adjustfield ) = ios:left ) . floatfield记录当前数字格式(科学记数法还是固定式)如:extern ostream os;if( ( os.flags() & ios:floatfield ) = ios:scientific ) .b、 标志和格式化访问函数flagsSets or reads the streams format flagssetfManipulates the streams format flagsunsetfClears the streams format flagsfillSets or reads the streams fill character(默认为空格)precisionSets or reads the streams floating-point format display precisionwidthSets or reads the streams output field width说明: flags函数有两个原型:fmtflags flags( ) const;/返回当前格式化标志值fmtflags flags( fmtflags fmtf);/设置格式化标志理解格式化标志:即流输出的格式,实作一般为一个32bit的整数,它的每一位表示一个标志,因此可以通过按位或方式同时设定多位标志。格式化常量有: enum _Fmtflags skipws = 0x0001, unitbuf = 0x0002, uppercase = 0x0004, showbase = 0x0008, showpoint = 0x0010, showpos = 0x0020, left = 0x0040, right = 0x0080, internal = 0x0100, dec = 0x0200, oct = 0x0400, hex = 0x0800, scientific = 0x1000, fixed = 0x2000, boolalpha = 0x4000, adjustfield = 0x01c0, basefield = 0x0e00, floatfield = 0x3000, _Fmtmask = 0x7fff, _Fmtzero = 0;详见vc安装目录下的xiosbase文件(此文件中定义了ios_base类,这是vc与标准C+不同的地方,标准C+中ios_base类定义在ios_base文件中) setf()原型 /示例代码ios:fmtflags oldFlags = cout.flags( );cout.setf (ios:showpos|ios:showbase|ios:uppercase);cout.flags(oldFlags);void setf ( fmtflags mask );/实际为调用flags (mask|flags),设定标志c、 流状态测试函数C+中定义了型别为iostate的4个常数;用以反映stream的状态常量 含义goodbit Everything is OK; none of the other bits is seteofbit End-of-file was encounteredfailbit Error; an I/O operation was not successfulbadbit Fatal error; undefined state测试函数则有如下数种:goodIndicates good stream statusbadIndicates a serious I/O erroreofIndicates end of filefailIndicates a serious I/O error or a possibly recoverable I/O formatting errorrdstateReturns the streams error flagsclearSets or clears the streams error flagsd、 ios中的manipulators(操控器、操作算子)manipulators是专门用来操控stream的对象(数据成员),常用来改变输入或格式化输出的解释方法。其中:ios中定义了dec、hex、oct而在ostream中定义了endl、ends(输出0)、flush在istream中定义了ws(读入并忽略空格)/例5-03#include void main()std:coutstd:hex123std:endl;e、 ios中带参数的manipulators(Parameterized Manipulators)注:必须#include 函数效果示例setiosflags按位设定格式化标志std:coutsetiosflags(std:ios:left)resetiosflagsResets the streams format flagssetfillSets the streams fill charactersetprecisionSets the streams floating-point display precisionsetwSets the streams field width (for the next field only)std:coutstd:setw(8)setfill(_)运算符。 ostream中相应定义了许多输出用函数,如put、write、flush以及seekg和tellp,并重载了运算符。8、 总的来说,应该 使用格式化标志设定流格式,使用格式化访问函数来访问和改变格式化标志; 使用流状态函数来测试流状态; 使用操控器来设定数据输出格式; 使用输入输出函数来读取、写入数据; 使用定位函数来获取当前位置和移动位置。9、 文件存取 为存取文件,C+提供了四个模板类和四个对应的char型特化版本basic_ifstream ifstream and wifstream basic_ofstream ofstream and wofstreambasic_fstream fstream and wfstream basic_filebuf filebuf and wfilebuf 如:typedef basic_ifstream ifstream; 与C的文件存取机制相比,C+的文件流的最大好处是文件的自动管理,文件可以构造时自动打开,在析构时自动关闭。 文件打开(处理)模式ios_base类定义了一组标志,其类型为openmode,是类似于fmtflags的位掩码类型。Flag Meaning in Opens for reading (default for ifstream) out Opens for writing (default for ofstream) app Always appends at the end when writingate Positions at the end of the file after opening (at end)trunc Removes the former file contentsbinary Does not replace special characters注:binary configures the stream to suppress conversion of special characters or character sequences such as end-of-line or end-of-file. In operating systems, such as MS-DOS or OS/2, a line end in text files is represented by two characters (CR and LF). In normal text mode (binary is not set), newline characters are replaced by the two-character sequence, and vice versa, when reading or writing to avoid special processing. In binary mode (binary is set), none of these conversions take place.如:std:ofstream file(xyz.out, std:ios:out|std:ios:app); 文件流类中的打开和关闭文件的成员函数Member Function Meaning open(name) Opens a file for the stream using the default modeopen (name, flags) Opens a file for the stream using flags as the mode close() Closes the streams fileis_open() Returns whether the file is opened/例5-04#include #include #include using namespace std;void main () ifstream file; std:string filename; char c; coutfilename; file.open(filename.c_str(),std:ios:in); while (file.get(c) cout.put(c); file.close();/提示:可直接输入main.cpp以打开这个文件/例5-05#include #include using namespace std;void main()/本程序向C:test.txt文件中输出1-94区的全部汉字及符号,/然后用记事本打开这个文件/每区前面先输出第几区,每区后空两行,每十个汉字成一行ofstream outfile(C:test.txt);/新建一个文本文件C:test.txtint i,j;char i1,i2;for(i=1;i95;i+)outfile第i区endl;/每区前面先输出第几区for(j=1;j95;j+)例5-05请参考第二单元下第十四类运行库函数中关于中文字符的说明char i1=i+0xA0;char i2=j+0xA0;outfilei1i2;if(!(j%10)outfileendl;/每十个汉字成一行outfileendlendl;/每区后空两行/用记事本打开文件/注意:记事本所有目录有可能不一样,如windows2000是在winnt目录下/而对windows98和windowsXP则在windows目录下 system(c:windowsNOTEPAD.EXE c:test.txt);/system(c:winntNOTEPAD.EXE c:test.txt); 文件的随机存取下表列出了在C+中用于在流中定位的函数ClassMember FunctionMeaningbasic_istreamtellg( )seekg(pos)seekg(offset, rpos)Returns the read positionSets the read position as an absolute valueSets the read position as a

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论