c++

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

小樊
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 函数进行格式化输出:
#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 将数值转换为字符串,然后进行拼接和格式化:
#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;
}

这些方法可以根据需要进行组合和修改,以实现所需的输出格式。

0
看了该问题的人还看了