在 C++ 的算法題中,如果你不知道輸入數據有多少組(即測試用例的數量未知),通常的處理方式是使用 循環讀取輸入直到文件結束 (EOF)。這類題目常見于在線評測系統(如 LeetCode、牛客網、POJ 等)。
? 常見方法:使用 while (cin >> 變量)
或 while (getline(cin, str))
📌 方法 1:適用于每組輸入有固定變量的情況
#include <iostream>using namespace std;int main() {int a, b;while (cin >> a >> b) {// 處理每一組輸入cout << a + b << endl;}return 0;}
- 這種寫法會持續讀取輸入,直到沒有更多輸入為止(遇到 EOF 結束循環)。
- 常用于像“多組輸入求 a + b”這種題目。
📌 方法 2:按整行讀取(適合復雜格式或含空格的輸入)
#include <iostream>#include <sstream>using namespace std;int main() {string line;while (getline(cin, line)) {// 每一行 line 是一組輸入istringstream iss(line);int a, b;if (iss >> a >> b) {cout << a + b << endl;}}return 0;}
- 使用
getline(cin, line)
來逐行讀取; - 再使用
istringstream
解析每一行的數據; - 更靈活,適合輸入格式較復雜的題目。
📌 方法 3:讀入多個數字的一組數據(比如每組輸入是一行多個數)
#include <iostream>#include <vector>using namespace std;int main() {string line;while (getline(cin, line)) {istringstream iss(line);int num;vector<int> nums;while (iss >> num) {nums.push_back(num);}// 處理這一組數據,例如求和int sum = 0;for (int x : nums) sum += x;cout << sum << endl;}return 0;}
?小結
場景 | 推薦寫法 |
---|---|
每組輸入幾個固定變量(如 a 和 b) |
|
輸入可能包含空格或一整行 |
|
每組輸入有多個不確定數量的數字 |
|
?補充說明
- 在本地調試時,可以通過輸入重定向或手動輸入后按下
Ctrl+Z
(Windows)或Ctrl+D
(Linux/macOS)來模擬 EOF。 - 在 OJ 平臺上,程序會自動從標準輸入讀取數據,直到輸入結束。