template and getchar()

来源:互联网 发布:象棋小鹤求败是软件 编辑:程序博客网 时间:2024/06/03 13:38

函数模板及重载函数模板

/* This is a studying of template of C++.**/#include <iostream>using namespace std;// To get the big one from two numbers.template <class type>type Sum(type a, type b){return a+b;}template<class type>type Max(type a, type b){if (a>b){return a;}else{return b;}}char * Max(char *a, char *b){if (strcmp(a,b)>0){return a;}else{return b;}}int main(void){int i;char a[20],b[20],sum[20];char *p;//a = NULL;//b = NULL;//sum = NULL;while(1){i = 0;cout<<"Please input two number to get the sum of the both : "<<endl<<"a=";//cin>>a;do {a[i] = getchar();i++;if (i>=20){break;}} while ((a[i-1]!='\n'));if (i>=20){a[19] = '\0';cout<<"We can only compare string less than 20 characters!sorry,overflow."<<endl;fflush(stdin);}elsea[i] = '\0';cout<<"b=";//cin>>b;i = 0;while((b[i]=getchar())!='\n'){i++;if (i>=20){break;}}if (i>=20){b[19] = '\0';cout<<"We can only compare string less than 20 characters!sorry,overflow."<<endl;fflush(stdin);}elseb[i] = '\0';//sum = Sum<float>(a,b);p = Max(a,b);cout<<"sum="<<p<<endl;}return 0;}
学习点:

1、模板的简单应用,注意书写方式;

2、getchar() :是宏定义函数,返回字符ASCII码值

    遇到此函数时,程序会等待键盘输入,而键盘输入会先保存在键盘缓冲区,遇到回车键才返回;

    注意字符在数组里面组成字符串时需要‘\0’标识符;

    比较字符是不是回车键时,不能用getchar()!=0x0D,而需要这种形式getchar()!='\n',现在还不知道这种差别?=====>是因为应该是0x0A对应才对,sorry

系统类型

回车换行所用字符

Linux/Unix

\n = Newline = 0x0A = 10 = LF =Line Feed = 换行 = Ctrl + J

Mac

\r = Return = 0x0D = 13 = CR = Carriage Return = 回车 = Ctrl + M

Windows/Dos

\r \n = 0x0D 0x0A = CR LF = 回车 换行


    为了不产生数组溢出,使用了break跳出,这里要注意清空键盘缓冲区,否则会影响下条接收语句

0 0
原创粉丝点击