首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 讀取含空白字符輸入的正確姿勢

     編輯:程式設計疑難解答

代碼審視

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;
    }
}

潛在問題

  1. getline 默認以 '\n' 為分隔符,不保留換行符,代碼手動補回,邏輯正確。
  2. 若輸入以 EOF 結束且無末尾換行,最後一行也不會遺漏。
  3. 性能隱患:逐字符輸出並頻繁刷新緩衝區(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 變量內容,確認空白字符是否正確捕獲。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved