代碼審視
string s;
while (getline(cin, s)) {
s += '\n'; // 手動補回換行符
for (auto c : s) {
if (c == ' ') cout << "yeah!space." << endl;
if (c == '\t') cout << "yeah!tab." << endl;
if (c == '\n') cout << "yeah!newline." << endl;
}
}
潛在問題
getline 默認以 '\n' 為分隔符,不保留換行符,代碼手動補回,邏輯正確。
- 若輸入以 EOF 結束且無末尾換行,最後一行也不會遺漏。
- 性能隱患:逐字符輸出並頻繁刷新緩衝區(
endl 會 flush),大數據量下極慢。建議改用 '\n' 並在循環外統一輸出或用 ostringstream。
改進版
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::string line;
std::ostringstream output;
while (std::getline(std::cin, line)) {
line += '\n';
for (char c : line) {
switch (c) {
case ' ': output << "yeah!space."; break;
case '\t': output << "yeah!tab."; break;
case '\n': output << "yeah!newline."; break;
}
output << '\n';
}
}
std::cout << output.str();
return 0;
}
調試技巧
- Visual Studio:
F9 設置斷點,F5 啟動調試,F10/F11 單步,Shift+F11 跳出函數。
- 觀察
line 變量內容,確認空白字符是否正確捕獲。