例题1:编写一个程序,读取键盘输入,直至遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写字符,将小写字符转换为大写字符:
#include <iostream>
#include <cctype> //cctype文件中的内容将读入到程序中。
int main()
{
using namespace std;
char ch;
cin.get(ch);
while(ch!='@');
{
if(is digit(ch));
cin.get(ch);
else
{ ch=tolower(ch);
cout<<ch;
cin.get(ch)
}
}
return 0;
}
#include<iostream>
#include<cctype>
using namespace std;
int main()
{
char ch;
cout<<"please enter:\n";
while (cin.get(ch)&&ch='@’);
{
if(islower(ch));
{
ch=toupper(ch);
cout<<ch;
}
else if(isupper(ch));
{
ch=tolower(ch);
cout<<ch;
}
else
cout<<ch;
}
return 0;
}
循环最常见的
任务:逐字符
地读取来自文件或者键盘的文本。例如:字符数,行数,字数的程序。
1)使用cin进行输入,那么何时知道停止读取,那么选择一个特殊字符就可以了例如:上面的程序读取到@这个字符时,程序停止:回显字符:在屏幕上显示这些字符:(注意,按下键盘上的键不能自动将字符显示到屏幕上,程序必须通过输入字符来完成这项工作
digit:数字:这个程序使用while,if语句来处理这个事件。
2)成员函数:cin.get(ch)//因为逐个输入的程序需要检查字符,包括空格,制表符,换行符.而cin.get(ch)//读取输入的下一个字符,即使它时空格,并将其赋给变量ch
替换cin>>ch, !=//表示不等于
cin.get(ch)有两个版本:
版本一:接受两个参数:数组名(字符串(char*类型)的地址)和Arsize(int类型的整数)
char name(Arsize);
…
cout<<“Enter your name:\n”;//:表示要输入,\n表示换行符
cin.get(name,Arsize).get();//最后一个相当于cin.get(),
版本二:char ch;
cin.get();//cin.get接受一个char参数。
字符函数库cctype:与字符相关的函数软件包(里面装了很多东西)函数的原型在头文件中定义,例如上面一个程序中,ch可能是数字,也可能是字符。
例二:编写一个程序,最多将10个donation值读入到一个double数组中(可以使用array)程序编写遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少数字大于平均值。
#include
#include
int main()
{
using namespace std;
double donation[10];
cin.get(donation);
while(donation!=‘isdigit’)
{
if(isdigit(donation));
cin.get(donation);
else
return 0
}
#include
#include
using namespace std;
int main()
{
double donation[10];
cout<<"
以上程序有误:对比
#include<iostream>
#include<cctype>
#include<array>
int main()
{
using namespace std;
double sum=0,average=0;
array<double,10>ad={0};
int i=0,total=0;
double temp;
while (cin>>temp&&<10&&!isdigit(temp))
{
ad[i]=temp;
sum+=ad[i];
++i;
}
if(i!=o)
average=sum/i;
for(int j=o;j<i;==j)
if(ad[j]>average)
++total;
cout<<"这些数字的平均值为“<<average<<endl;
cout<<"并且共有”<<total<<"个数字大于平均值.\n";
return 0;
}