本文主要幫助刷leetcode題型快速適應完整帶輸入輸出的題(機試、考試、比賽等)
接收能用cin就用cin 。cin
?自動分割單詞?的特性(cin
?讀取字符串時會自動跳過空格 / 換行,將連續非空格字符作為一個 “單詞”)
一、單組輸入(僅一組數據)
1. 單個整數 / 浮點數
// 輸入:5
int a;
cin >> a;// 輸入:3.14
double b;
cin >> b;
2. 多個整數 / 浮點數(空格分隔)
// 輸入:1 2 3 4
int a, b, c, d;
cin >> a >> b >> c >> d;// 輸入:1.5 2.0 3.7
double x, y, z;
cin >> x >> y >> z;
3. 單個字符串(無空格)
// 輸入:hello
string s;
cin >> s; // cin遇空格/換行終止,適合無空格字符串
4. 一行帶空格的字符串
// 輸入:hello world
string s;
getline(cin, s); // 讀取整行(包括空格),需注意前面是否有殘留換行符
二、多組輸入(已知行數)
1. 先輸入行數 n,再輸入 n 組數據
// 輸入:
// 3
// 1 2
// 3 4
// 5 6
int n;
cin >> n;
while (n--) {int a, b;cin >> a >> b;// 處理每組a,b
}
2. 已知矩陣行列數(如 n 行 m 列)
// 輸入:
// 2 3
// 1 2 3
// 4 5 6
int n, m;
cin >> n >> m;
vector<vector<int>> mat(n, vector<int>(m));
for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {cin >> mat[i][j];}
}
三、多組輸入(未知行數,以 EOF 結束)
1. 持續讀取直到輸入結束(控制臺按Ctrl+Z
終止)
// 輸入:
// 1 2
// 3 4
// 5 6
// (Ctrl+Z+回車結束)
int a, b;
while (cin >> a >> b) { // cin讀取失敗時返回false// 處理每組a,b
}
2. 讀取未知行數的字符串(每行一個)
// 輸入:
// first line
// second line
// third line
// (Ctrl+Z+回車結束)
string s;
while (getline(cin, s)) { // getline讀取失敗時返回false// 處理每行s
}
四、多組輸入(以特定值終止)
1. 以 0 0 或 - 1 -1 等特殊值結束
// 輸入:
// 1 2
// 3 4
// 0 0 (終止標志)
int a, b;
while (cin >> a >> b) {if (a == 0 && b == 0) break; // 遇到終止標志退出// 處理每組a,b
}
2. 以空行終止(字符串輸入)
// 輸入:
// hello
// world
// (空行)
string s;
while (getline(cin, s)) {if (s.empty()) break; // 空行終止// 處理每行s
}
五、字符串與數值混合輸入
1. 一行中包含字符串和整數
// 輸入:abc 123 def 456
string s1, s2;
int a, b;
cin >> s1 >> a >> s2 >> b;
2. 先讀整數,再讀帶空格的字符串(需處理殘留換行符)
// 輸入:
// 2
// hello world
// test case
int n;
cin >> n;
cin.ignore(); // 忽略n后的換行符,否則getline會讀空行
while (n--) {string s;getline(cin, s);// 處理s
}
六、特殊分隔符輸入(非空格 / 換行)
1. 逗號分隔的整數
// 輸入:1,2,3,4,5
string s;
getline(cin, s);
replace(s.begin(), s.end(), ',', ' '); // 逗號替換為空格
stringstream ss(s); // 用stringstream解析
int x;
while (ss >> x) {// 依次讀取1,2,3,4,5
}
2. 冒號分隔的鍵值對
// 輸入:a:1 b:2 c:3
string s;
while (cin >> s) {size_t colon = s.find(':');string key = s.substr(0, colon);int val = stoi(s.substr(colon + 1));// 處理key和val
}
七、大數據量輸入(優化速度)
當輸入數據量極大(如 1e5+)時,用cin
可能超時,需優化:
// 方法1:關閉cin同步(與stdio兼容)
ios::sync_with_stdio(false);
cin.tie(0);
// 之后正常用cin >> ...// 方法2:用scanf(速度更快)
int a, b;
while (scanf("%d %d", &a, &b) != EOF) {// 處理a,b
}
八、輸出常見形式
1. 單個 / 多個值(空格分隔,換行結尾)
int a = 1, b = 2;
cout << a << " " << b << endl; // 輸出:1 2
2. 數組 / 矩陣輸出
vector<int> arr = {1,2,3,4};
for (int x : arr) {cout << x << " "; // 輸出:1 2 3 4 (末尾多一個空格,機試通常不報錯)
}
cout << endl;// 矩陣(每行換行)
vector<vector<int>> mat = {{1,2},{3,4}};
for (auto& row : mat) {for (int x : row) {cout << x << " ";}cout << endl;
}
3. 字符串輸出(保留空格)
string s = "hello world";
cout << s << endl; // 輸出:hello world
4. 無換行連續輸出
// 輸出:1234(無空格無換行)
cout << 1 << 2 << 3 << 4;
以上涵蓋了算法題中 95% 以上的輸入輸出場景,核心是根據輸入格式選擇cin
/scanf
(數值 / 無空格字符串)或getline
(帶空格字符串 / 整行),并注意處理多組輸入的終止條件。