温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++编程:tostring与格式化输出

发布时间:2024-09-08 18:13:35 来源:亿速云 阅读:83 作者:小樊 栏目:编程语言

在 C++ 中,std::to_string() 函数用于将数字类型(如 int、float、double 等)转换为字符串。而格式化输出可以通过 std::coutstd::printf 实现。下面是一些示例:

  1. 使用 std::to_string() 将数字转换为字符串:
#include<iostream>
#include<string>

int main() {
    int num = 42;
    std::string str_num = std::to_string(num);
    std::cout << "Number as string: "<< str_num<< std::endl;
    return 0;
}
  1. 使用 std::cout 进行格式化输出:
#include<iostream>
#include <iomanip> // 引入 iomanip 头文件以使用 setw, setprecision 等操作符

int main() {
    double pi = 3.141592653589793;
    std::cout << "Formatted output with std::cout:"<< std::endl;
    std::cout << "PI with 2 decimal places: "<< std::fixed<< std::setprecision(2) << pi << std::endl;
    std::cout << "PI with 5 decimal places: "<< std::fixed<< std::setprecision(5) << pi << std::endl;
    return 0;
}
  1. 使用 std::printf 进行格式化输出:
#include<iostream>
#include <cstdio> // 引入 cstdio 头文件以使用 printf

int main() {
    double pi = 3.141592653589793;
    std::printf("Formatted output with std::printf:\n");
    std::printf("PI with 2 decimal places: %.2f\n", pi);
    std::printf("PI with 5 decimal places: %.5f\n", pi);
    return 0;
}

这些示例展示了如何在 C++ 中使用 std::to_string() 函数将数字转换为字符串,以及如何使用 std::coutstd::printf 进行格式化输出。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI