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

   2024-09-30 2660
核心提示:在 C++ 中,可以使用多种方法来格式化控制台输出。以下是一些常见的方法:使用 std::cout 和 std::setw 设置输出宽度:#includei

在 C++ 中,可以使用多种方法来格式化控制台输出。以下是一些常见的方法:

使用 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;}
使用 std::printf 函数进行格式化输出:
#include <cstdio>int main() {    const char* name = "Alice";    int age = 25;    std::printf("Name: %s, Age: %d\n", name, age);    return 0;}
使用 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;}
使用 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;}

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号