2012年6月3日星期日

从c++开始6

值的类型将引导cin 和 cout 如何显示值

#include "stdafx.h"
#include <iostream>
int main()
{
                 using namespace std;
                 char c;//定义了一个character类新的变量没有赋值
                cout<< "Enter a character: " <<endl;
                cin>>c;//通过键盘输入一个字母
                cout<< "Hellow!" ;
                cout<< "Thank you for the " <<c<<"character." <<endl;//将该char类型的字母插入cout
                 int m;
                cin>>m;
    return 0;
}

如下显示: 
Enter a character:
m
Hellow!Thank you for the mcharacter.

cout.put() 是什么? cout 是类的对象,put()是类的成员函数,中间的句点是连接符。就是类的对象使用类的函数的意思。cout.put() 就是一种显示字符的方法,以前是用 << 操作符来执行的,是根据值的类型将引导cin 和 cout 如何显示值的定义。那么为何用到 cout.put ? 是有历史原因的,在早期的c++中处理这种情况跟c 一样的, cout 可以将字符变量显示出字符没问题,但是字符常量呢? 例如单引号的 'M' ,就会被显示成数字,并储存为integer类型.就是早期的 cout<< "M"  不能显示M 而是对应的ASCII 码77。

但是如今的c++ 修正了这一点. 也可以将字符常量显示为字符. 
貌似这个列子是多余的? 只不过是为了让大家了解" 类 , 对象, 成员函数" 的调用方法而已.

#include "stdafx.h"
#include <iostream>

int main()
{
                 using namespace std;
                 char c = 'M' ; //用单引号single quotes的 M 就是将其对应ASCII 码赋值给了变量c。
                 int i = c; //  int i 变量又使用了c作为它的值。
                cout << "The ASCII code for " <<c<<"is" <<i<<endl;
                cout << "Add one to the character code; " <<endl;
                c=c+1; // c+1 = 77+1 也就是大写N 对应的ASCII值
                i=c;
                cout<< "The ASCII code for " <<c<<" is " <<i<<endl;
                cout<< "Displaying char c using out.put(c): " ;
                cout.put(c); // 调用 cout.put 函数将c 也就是78转变成 N 
                cout.put( '!' ); // 直接用 cout.put 输出单引号的 !。
                cout<<endl<< "Done" <<endl;
                 int m;
                cin>>m;
                 return 0;
}

如下显示:
The ASCII code for Mis77
Add one to the character code;
The ASCII code for N is 78
Displaying char c using out.put(c): N!
Done

没有评论:

发表评论