2017年10月26日 星期四

程式設計I -- 陣列和字串筆記


1. 陣列填滿所有一樣的數字
加上include<algorithm>,使用fill()
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int buf[5];
fill(buf, buf + 5, 1);
//(陣列起始位置, 陣列結束位置,填入的數字)
//buf代表buf[0]
//buf+5代表buf[0+5]
return 0;
}

2. 拷貝陣列
加上include<algorithm>,使用copy()
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
        int buf[5] = { 1,2,3,4,5 };
        int buf2[5];
        copy(buf, buf + 5, buf2);
        //把buf從0到buf的尾巴的內容,複製到buf2的陣列中
        return 0;
}

3. getline讀字串讀到空白的解決方法
#include<iostream>
#include<string>
using namespace std;

int main()
{
int value;
  cin >> value;
  cin.ignore(); //呼叫 ignore 忽略緩衝區的資料
  for (int i = 0; i < value; i++)
  {
  string s;
  getline(cin, s);
  cout << "[output] string " << i+1 << ": \"" << s + "\""<< endl;
  }
}

4. 字串拷貝
#include<iostream>  
#include<iomanip>  
#include<string>
using namespace std;
int main()
{
        string s = "hi";
        string s2(s);      //把 s 拷貝給 s2
        string s3 = s;    //把 s 拷貝給 s3
        cout << s2 << endl;
        cout << s3 << endl;
        return 0;

}

5. 字串逆轉
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
  string s = "100";
  reverse(s.begin(), s.end());
  cout << s << endl;
  return 0;
}

6. 

沒有留言:

張貼留言