溫馨提示×

C++ console輸出的格式化方法有哪些

c++
小樊
84
2024-09-04 19:51:11
欄目: 編程語言

在 C++ 中,可以使用多種方法來格式化控制臺輸出。以下是一些常見的方法:

  1. 使用 std::coutstd::setw 設置輸出寬度:
#include<iostream>
#include <iomanip>

int main() {
    std::cout << "Name"<< std::setw(10) << "Age"<< std::endl;
    std::cout << "Alice"<< std::setw(10) << "25"<< std::endl;
    std::cout << "Bob"<< std::setw(10) << "30"<< std::endl;
    return 0;
}
  1. 使用 std::printf 函數(shù)進行格式化輸出:
#include <cstdio>

int main() {
    const char* name = "Alice";
    int age = 25;
    std::printf("Name: %s, Age: %d\n", name, age);
    return 0;
}
  1. 使用 std::ostringstreamstd::setw 對字符串進行格式化:
#include<iostream>
#include <iomanip>
#include <sstream>
#include<string>

int main() {
    std::ostringstream oss;
    oss << "Name"<< std::setw(10) << "Age"<< std::endl;
    oss << "Alice"<< std::setw(10) << "25"<< std::endl;
    oss << "Bob"<< std::setw(10) << "30"<< std::endl;

    std::string formatted_output = oss.str();
    std::cout<< formatted_output;
    return 0;
}
  1. 使用 std::to_string 將數(shù)值轉(zhuǎn)換為字符串,然后進行拼接和格式化:
#include<iostream>
#include<string>

int main() {
    std::string name = "Alice";
    int age = 25;
    std::string output = "Name: " + name + ", Age: " + std::to_string(age);
    std::cout<< output<< std::endl;
    return 0;
}

這些方法可以根據(jù)需要進行組合和修改,以實現(xiàn)所需的輸出格式。

0