字串,就是把一堆字元串起來的意思。
例如 "Hello"
、"^_^"
、"Rock!"
在C++裡,可以用 char[ ] 或 string 儲存字串
以下僅先介紹 char[ ] 的使用方式
是指利用字元(char)陣列儲存字串。
跟陣列使用一樣,要先估計最多會儲存幾個半形字,直接宣告到最大大小,再多預留一些空間
可以直接利用 cin
/ cout
輸出入一串沒有空白或換行的字
Hello
Your name is Hello
#include<iostream>
using namespace std;
int main()
{
char name[55];
cin >> name;
cout << "Your name is " << name << endl;
return 0;
}
上一個範例裡,明明 name
陣列總共有55格,C++是如何知道只需要輸出Hello
就該停下呢?
cin
時,C++會自動在char[]
裡最後一個字元的後一格放上 '\0'
來標記結束
cout
時,C++也會逐一輸出char[]
裡的字元,直到碰到'\0'
為止
cout << name;
可以想成是
for( i=0 ; name[i] != '\0' ; i=i+1 )
cout << name[i];
'\0'
ASCII數字編號0,是NULL
、空集合
的意思
一串字 和 一個整數n,以空白隔開
只輸出前n個字
Rock 3
spaceship 5
butterfly 6
Roc
space
butter
\0
放置版\0
放在特定位置,則後面的字都不會被輸出#include<iostream>
using namespace std;
int main()
{
char s[55];
int n;
while( cin >> s >> n )
{
s[n] = '\0';
cout << s << endl;
}
return 0;
}
for
控制要輸出到第幾格#include<iostream>
using namespace std;
int main()
{
char s[55];
int n, i;
while( cin >> s >> n )
{
for( i=0 ; i<n ; i++ )
{
cout << s[i];
}
cout << endl;
}
return 0;
}
下列 code 和 input1,2 搭配起來會有什麼 output? 為什麼?
#include<iostream>
using namespace std;
int main()
{
char name[100];
//1st
cin >> name;
//2nd
cin >> name;
cout << name << endl;
return 0;
}
shortname
longlongname
longlongname
shortname
Q10929: You can say 11 http://luckycat.kshs.kh.edu.tw/homework/q10929.htm
Q11192: Group Reverse http://luckycat.kshs.kh.edu.tw/homework/q11192.htm
Q10340: All in All http://luckycat.kshs.kh.edu.tw/homework/q10340.htm