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

C++ 字串拼接加逗號空格:現代 C++ 優雅寫法與 C 風格對比

     編輯:程式設計疑難解答

需求

輸入名、姓,輸出「名, 姓」格式(逗號+空格分隔)。

方案一:std::string + 運算子+(推薦,現代 C++)

#include <iostream>
#include <string>
int main() {
    std::string first, last;
    std::cout << "Enter first name: ";
    std::getline(std::cin, first);
    std::cout << "Enter last name: ";
    std::getline(std::cin, last);
    std::string full = first + ", " + last;
    std::cout << "Result: " << full << '\n';
}
  • 記憶體自動管理、無緩衝區溢位風險、支援 Unicode。

方案二:std::format (C++20)

#include <format>
#include <iostream>
#include <string>
int main() {
    std::string first, last;
    std::getline(std::cin, first);
    std::getline(std::cin, last);
    std::cout << std::format("{}, {}", first, last) << '\n';
}
  • 型別安全、格式字串可讀性高、效能優於 iostream。

方案三:std::ostringstream(舊專案相容)

#include <sstream>
#include <iostream>
#include <string>
int main() {
    std::string first, last;
    std::getline(std::cin, first);
    std::getline(std::cin, last);
    std::ostringstream oss;
    oss << first << ", " << last;
    std::cout << oss.str() << '\n';
}

方案四:C 風格 char 陣列 + strcat(教學用,不建議生產)

#include <cstring>
#include <iostream>
int main() {
    const int N = 40;
    char first[N], last[N], full[2*N];
    std::cin.getline(first, N);
    std::cin.getline(last, N);
    strcpy(full, first);
    strcat(full, ", ");
    strcat(full, last);
    std::cout << full << '\n';
    // 風險:緩衝區溢位、手動管理記憶體、不支援 Unicode
}

關鍵差異總結表

指標std::stringstd::formatchar[]+strcat
安全性高高低
可讀性高最高低
效能中高高(但危險)
標準C++98C++20C89

建議

  • C++17/20 專案:**優先 std::format**,次選 std::string。
  • 舊標準專案:std::string 或 ostringstream。
  • 嚴禁在新專案使用 strcat/sprintf 處理使用者輸入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved