将 int 转换为 C++ 中带有 2 位数字的字符串

Convert an int to a string with 2 digits in C++

本文关键字:数字 字符串 转换 int C++      更新时间:2023-10-16

我在C++中有以下代码,它应该采用led_pwm十六进制变量,并将其转换为字符串led_pwm_string

long int led_pwm=0x0a;
std::ostringstream ostr;
ostr << std::hex << led_pwm; //use the string stream just like cout,
                             //except the stream prints not to stdout 
                             //but to a string.
std::string led_pwm_string = ostr.str(); //the str() function of the stream
                                         //returns the string

我对这段代码的唯一问题是,对于 0x000x0a 之间的任何 led_pwm 值,它会转换为 led_pwm_string 的一位数。这给以后的我带来了问题。

我希望,在各种可能的情况下,led_pwm_string始终包含一个 2 位字符串。因此,如果led_pwm0x01(例如),那么led_pwm_string将被01,而不仅仅是1

尝试:

ostr << std::hex << std::setw(2) << std::setfill('0') << led_pwm;

您可能需要#include <iomanip>