设为首页 加入收藏

TOP

二级C++输入输出流:键盘输入
2014-11-19 05:13:58 】 浏览:3928
Tags:二级 输入 输出 键盘

1 、使用预定义的提取符:


最一般的键盘输入是将提取符作用在流类的对象 cin 上。


格式: cin>>< 表达式 >>>< 表达式 > ……


说明:⒈从键盘上输入的两个 int 型数之间用空白符分隔,一般常用空白符,也可以用 tab 键或换行符。


2.提取符可以输入流中读取一个字符序列,即一个字符串。


例 4 :分析下列程序的输出结果:


#include


#include


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<


cout<


cout<


cout<


}


执行如下: 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


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


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#”<


cout.write(buf,count).put(‘\n').put(‘\n');


}


cout<


cout<<”Total Line:”<


cout<<”Longest Line:”<


}


3 、使用成员函数 read() 读取一串字符:


格式: cin.read(char *buf,int SIZE)


功能:从输入流中读取指定的数目的字符,并将它们存放在指定的数组中。


例 6 : #include


void main()


{


const int S=80;


char buf[S]=” “;


cout<<”Input…..\n”;


cin.read(buf,S);


cout<


cout<


}


Input…..


Abcd


Efgh


Ijkl



输出: abcd


efgh


ijkl


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇二级C++输入输出流:屏幕输出 下一篇二级C++输入输出流:磁盘文件的输..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目