C++ ostream類爲下面的指針類型定義了插入運算符函數:
const signed char *;
const unsigned char *;
const char *;
void *;
C++用指向字符串存儲位置的指針來表示字符串,指針的形式可以是char數組名,顯式的char指針或用引號括起來的字符串。 下面是一個簡單輸出字符串的例子:
#include <iostream>
using namespace std;
int main()
{
char name[] = "Kecily!";
char *Name = "yuting";
cout << name << endl;
cout << Name << endl;
}
輸出結果是:
Kecily!
yuting
看看下面這個例子可看出以下用法的區別:
#include <iostream>
using namespace std;
int main()
{
char name[] = "Kecily!";
char *Name = "yuting";
cout << name << endl;
cout << *Name << endl;
}
輸出時,結果是:
Kecily!
y
解析: 因爲字符串指針指向的是整個字符串的起始地址,代表的是整個字符串,而*Name指向的是這個字符串的第一個字符,所以輸出的結果將是所指向字符串的第一個字符;
那如果我要輸出指向這個字符串的指針的地址呢,也就是指針的值;
思路解析: 對於其他類型的指針,如果要對其地址的輸出,直接輸出其指針即可,但是對於字符串不一樣,因爲其本身的指針名代表了整個字符串,所以就需要用另外一種表示方法對其地址進行輸出:
#include <iostream>
using namespace std;
int main()
{
int m = 59;
char *name = "yuting";
cout << &m << endl;
cout << (void *)name << endl;
}
另外介紹一下兩種cout對象輸出字符和字符串的另外兩種方法,就是put和write,直接使用cout對象調用輸出;
先說put吧, put適用於字符輸出,但是也可以對整型數字進行輸出,不過進行put調用輸出後的整型數字就自動轉換成了char型數字字符了,輸出對應ASCII字符值;
而且哦,put還可以拼接輸出哦,好強大!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
string name = "Kecily";
for(i=0; i<name.length()-1; i++) {
cout.put(name[i]).put('-'); //對象調用輸出,以及拼接輸出;
}
cout.put(name[i]).put('\n');
}
輸出結果:
K-e-c-i-l-y
#include <iostream>
using namespace std;
int main()
{
int m = 67;
cout.put(m).put('\n');
}
結果是: C
write函數的原型:
basic_ostream<charT, traits>& write(const char_type* s, streamsize n);
第一個參數爲要顯示的字符串的地址,第二個參數爲要顯示字符串的多少個字符;
這個函數有點奇怪,看一下例子吧:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const char *str = "XiaoHui";
int len = std::strlen(str);
for(int i=1; i<=len; i++) { //注意喔,這裏是從1開始喔;
cout.write(str, i) << endl;
}
return 0;
}
如果註釋處事從0開始的話,輸出會跟預計的不一樣;
運行結果:
X
Xi
Xia
Xiao
XiaoH
XiaoHu
XiaoHui
另外,write函數並不會在遇到空字符時自動停止打印字符,而是打印指定數目的字符:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
const char *s1 = "hello world!";
const char *s2 = "bai bu chuan yang!";
int len = std::strlen(s1);
cout.write(s1, len+8) << endl;
}
輸出:
hello world! bai bu