C++学习笔记(一)
本文主要內容為C++下的輸入輸出函數以及for循環中的C++11新特性。
一、輸入輸出函數
1. cin
cin 遇到 空格、回車、Tab結束輸入, 且會將讀到的空格、回車、Tab 丟棄,例:
#include<iostream> using namespace std;int main(void) {char a[10];cin >> a;cout << a << endl; //第一次輸出cin >> a;cout << a << endl; //第二次輸出return 0; }Test:
由圖像可見,在輸入時,若輸入兩串字符,即便程序需要輸入兩次,第二次讀取不會再次手動從鍵盤輸入,而是上次輸入的空格后的內容成為第二次讀入的字符串。類似于scanf。
2. cin.get()
1) cin.get()有三種形式:
ch = cin.get();
cin.get( ch );
cin.get( str, size );
注:前兩個用于讀取字符,第三個用于讀取字符串。cin.get()不會丟棄讀到的空格、回車,即第一個cin.get()讀到 Space 或 Enter 后,停止讀取數據,在第二次的cin.get()中,會將上次讀取到的 Space 或 Enter 存到字符中,而不是繼續讀取結束符后面的數據。
Test:
2) 在使用cin.get(str, size)讀取字符串時,同樣會遇到Space與Enter結束輸入,而且不會將最后讀到的Space與Enter丟棄,所以會造成后續cin.get()無法繼續讀入應有的字符串。PS:可用cin.clear()來清除
Test:
3. cin.getline()
cin.getline(str, size);用于讀取一行字符串,限制讀入size - 1個字符,會自動將讀到的Enter丟棄,且會在字符串最后添加\0作為結束符。然而,如果一行字符串長度超過 size ,會造成多余字符丟失。
#include<iostream> using namespace std;int main(void) {char a[3], b[3], c[3];cin.getline(a, 3);cin.getline(b, 3);cin.getline(c, 3);cout << "output : " << a << endl;cout << "output : " << b << endl;cout << "output : " << c << endl;return 0; }Test :
圖中兩次運行程序均只輸入了一次,第一次輸入`abcdefg`,測試長度超限,第二次測試空格對其影響。二、循環(C++11 新特性)
C++11新增了一種循環:基于范圍(range-based)的for循環。
(吐槽一下~~,雖然在學C++,但是總是會想到Python,因為好多東西貌似Python……,就比如這個range-based,Python的循環為for i in range(1. 10), 遍歷1 <= i < 10)
ok,開始正題:
1)遍歷
#include<iostream> using namespace std;int main(void) {int number[5] = {3, 2, 1, 5, 4};cout << "Output :" << endl;for(int x : number) //warning: 此處為 :, 而不是 ;cout << x << ' ';cout << endl;return 0; }for循環的含義為:變量x在數組number中遍歷,且x代表數組中被指向的元素Test :
2)修改數組元素
#include<iostream> using namespace std;int main(void) {int number[5] = {3, 2, 1, 5, 4};for(int &x : number)x *= 2; //將數組中每個元素乘2cout << "Output :" << endl;for(int x : number)cout << x << ' ';cout << endl;return 0; }for循環中定義了`&x`,&表明x為引用變量,即改變x的值可以直接改變數組中對應元素的值。Test :
3)for循環與初始化列表的結合
#include<iostream> using namespace std;int main(void) {cout << "Output :" << endl;for(int x : {5, 4, 1, 2, 3})cout << x << ' ';cout << endl;return 0; }x將遍歷列表{5, 4, 1, 2, 3}中的值Test :
本次的筆記(一)暫時到此為止,如有不足會持續更新、添加。
總結
以上是生活随笔為你收集整理的C++学习笔记(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 游戏崩溃
- 下一篇: C++学习笔记(二)