- 1、本文档共37页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
不带参数的get函数 cin.get() #include iostream using namespace std; int main( ) { int c; //NOTE: int ,not char!!! coutenter a sentence:endl; while( ( c=cin.get() ) != EOF ) cout.put(c); } 运行情况如下: enter a sentence: I study C++ very hard.↙ I study C++ very hard. ^Z↙(程序结束) EOF:文件结束符,一般为-1 带一个参数的get函数cin.get(ch) #include iostream using namespace std; void main( ) { char c; coutenter a sentence:endl; while(cin.get(c)) cout.put(c); coutendendl; } 带三个参数的get函数cin.get(字符数组(或字符指针),字符个数n,终止字符) #include iostream using namespace std; int main( ) { char ch[20]; cout″enter a sentence:″endl; cin.get(ch,10,’\n’); //指定换行符为终止字符 coutchendl; return 0; } 运行情况如下: enter a sentence: I study C++ very hard.↙ I study C 可以省略,默认为’\n’ 读入n-1个字符 3. getline函数 cin.getline(字符数组(或字符指针),字符个数n,终止标志字符) 从输入流中读取一行字符 #include iostream using namespace std; int main( ) {char ch[20]; coutenter a sentence:endl; cinch; coutThe string read with cin is:chendl; cin.getline(ch,20,/); //读19个字符或遇′/′结束 coutThe second part is:chendl; cin.getline(ch,20); //读19个字符或遇′/n′结束 coutThe third part is:chendl; return 0; } enter a sentence: I like C++./I study C++./I am happy.↙ 程序运行情况如下: enter a sentence: I like C++./I study C++./I am happy.↙ The string read with cin is:I The second part is: like C++. The third part is:I study C++./I am h get getline cin几点区别 getline函数从输入流读字符时,遇到终止标志字符时结束,指针移到该终止符之后,下一个getline函数接着读入。 get函数从输入流读字符时,遇终止标志字符时停止读取,指针不向后移动,停留在原位置。下一次读取仍从该终止标志字符开始。 cin读取数据时以空白字符作为终止标志,cin.getline()可以连续读取一系列字符,包括空格。 4. ignore函数 调用形式:cin.ignore(n, 终止字符) 作用: 跳过输入流中n个字符,或在遇到指定的终止 字符时提前结束(此时跳过包括终止字符在内的若干 字符)。 cin.ignore(10,’t’); //跳过输入流中10个字符,或遇到’t’后就不再跳了不带参数或只带一个参数 如: ignore( ) //只跳过1个字符(默认值为1,终止字符默认为EOF) 相当于ignore(1,EOF) #include iostream using namespace std; int main( ) { char ch[20]; cin.get(ch,20,/); coutThe first part is:chendl; cin.ignore( );//跳过输入流中一个字符 cin.get(ch,20,/); coutThe second part is:chendl; return 0; } 运行结果
文档评论(0)