![]() ![]() |
|
二级C++输入输出流:键盘输入 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/4/18 14:40:15 文章录入:杜斌 责任编辑:杜斌 | |
|
|
1 、使用预定义的提取符: 最一般的键盘输入是将提取符作用在流类的对象 cin 上。 格式: cin>>< 表达式 >>>< 表达式 > …… 说明:⒈从键盘上输入的两个 int 型数之间用空白符分隔,一般常用空白符,也可以用 tab 键或换行符。 2.提取符可以输入流中读取一个字符序列,即一个字符串。 例 4 :分析下列程序的输出结果: #include<iostream.h> #include<string.h> void main() { const int SIZE=20; char buf[SIZE]; char *largest; int curlen,maxlen=-1,cnt=0; cout<<”Input words:\n”; while (cin>>buf) { curlen=strlen(buf); cnt++; if(curlen>maxlen) { maxlen=curlen; largest=buf; } } cout<<endl; cout<<cnt<<endl; cout<<maxlen<<endl; cout<<largest<<endl; } 执行如下: Input words: if else return do while switch case for goto break continue (Ctrl+Z) 2 、使用成员函数 get() 获取一个字符: 格式: cin.get(char &ch) 功能:可以从输入流获取一个字符,并把它放置到指定变量中。 例 5 :当从键盘上输入如下字符序列时,分析输出结果: abc xyz 123 #include <iostream.h> void main() { char ch; cout<<”input:”; while((ch=cin.get())!=EOF) cout.put(ch); cout<<”OK!”; }
注解 :⒈ EOF 是个符号常量,其值为 -1 。 ⒉ get() 函数还可以在程序中这样使用: char ch; cin.get(ch); // 从输入流中读取一个字符存放在 ch 中。 Cout.put(ch); //ch 中的字符显示在屏幕上。 ⒊ getline(): 功能是可以从输入流中读取多个字符。 格式: cin.getline(char *buf,int limit ,deline='\n'); 其中: (1)buf 是一个字符指针或一个字符数组。 (2)limit 用来限制从输入流中读取到 buf 字符数组中的字符个数,最多只能读 limit-1 个,留 1 个放结束符。 (3)deline 读取字符时指定的结束符。 例 5 :编程统计从键盘上输入每一行字符的个数,从中选出最长的行的字符个数,统计共输入多少行? #include<iostream.h> const int SIZE=80; void main() { int lcnt=0,lmax=-1; char buf[SIZE]; cout<<”Input ……..\n”; while (cin.getline(buf,SIZE)) { int count=cin.gcount(); lcnt++; if(count>lamx) lamx=xount; cout<<”Line#”<<lcnt<<”\t”<<”chars read:”<<count<<endl; cout.write(buf,count).put(‘\n').put(‘\n'); } cout<<endl; cout<<”Total Line:”<<lcnt<<endl; cout<<”Longest Line:”<<lamx<<endl; } 3 、使用成员函数 read() 读取一串字符: 格式: cin.read(char *buf,int SIZE) 功能:从输入流中读取指定的数目的字符,并将它们存放在指定的数组中。 例 6 : #include<iostream.h> void main() { const int S=80; char buf[S]=” “; cout<<”Input…..\n”; cin.read(buf,S); cout<<endl; cout<<buf<<endl; } Input….. Abcd Efgh Ijkl <ctrl+z> 输出: abcd efgh ijkl |
|
![]() ![]() |