Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Khác biệt giữa printf() và cout trong C++

printf() - C Standard Library

  • Hàm variadic: int printf(const char* format, ...)
  • Format specifier: %d, %s, %f, %p...
  • Trả về số ký tự in (hoặc âm nếu lỗi)
  • Không type-safe: compiler không check format vs argument (trừ warning)
  • Nhanh hơn một chút cho output đơn giản
  • Có trong <cstdio>

Ví dụ

#include <cstdio>

int main() {
    int a = 24;
    printf("Welcome!\n");
    printf("Value: %d, Hex: 0x%X, Float: %.2f\n", a, a, 3.14);
    return 0;
}

cout - C++ iostream

  • Object std::ostream (thường là std::cout)
  • Toán tử << nạp chồng cho mọi kiểu
  • Type-safe: compile error nếu kiểu không hỗ trợ
  • Extensible: overload operator<< cho kiểu tự định nghĩa
  • Sync với stdio mặc định (chậm hơn) - có thể tắt: std::ios::sync_with_stdio(false)
  • Có trong <iostream>

Ví dụ

#include <iostream>

int main() {
    int a = 28;
    std::cout << "Value: " << a << ", Hex: " << std::hex << a << std::dec << '\n';
    return 0;
}

So sánh chi tiết

Tối ưu cout cho hiệu năng

int main() {
    // Tắt sync với stdio - QUAN TRỌNG cho hiệu năng
    std::ios::sync_with_stdio(false);
    // Untie cin/cout - nhanh hơn khi xen kẽ input/output
    std::cin.tie(nullptr);
    
    // Nay printf và cout có tốc độ ngang nhau
    for (int i = 0; i < 1000000; ++i) {
        std::cout << i << '\n';
    }
}

Khi nào dùng cái nào?

  • printf: Code C, embedded, format phức tạp, logging C-style, cần tốc độ tối đa không sync
  • cout: Code C++ hiện đại, type safety, custom type, RAII streams, locale-aware
  • Best practice: Chọn một style cho project. C++ mới: ưu tiên iostream + fmt library / std::format (C++20)

C++20: std::format - Best of both worlds

#include <format>
#include <iostream>

int main() {
    std::cout << std::format("Value: {}, Hex: {:x}, Float: {:.2f}\n", 42, 42, 3.14);
    // Type-safe, format string như printf, extensible
}
Đặc điểmprintf()cout
Type safetyKhông (runtime)Có (compile-time)
ExtensibilityKhó (custom specifier)Dễ (operator<<)
Format controlFormat string mạnhIomanip (verbose)
Hiệu năng (sync on)Nhanh hơnChậm hơn
Hiệu năng (sync off)Tương đươngTương đương/nhanh hơn
Thread safetyPer-call atomicPer-stream (cần sync thủ công)
LocalizationLocale Cstd::locale support