【问题标题】:Convert an int to a string with 2 digits in C++在 C++ 中将 int 转换为具有 2 位数字的字符串
【发布时间】:2023-03-19 01:54:01
【问题描述】:

我在 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

【问题讨论】:

    标签: c++ formatting converters


    【解决方案1】:

    试试:

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

    您可能需要#include &lt;iomanip&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2011-07-11
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      相关资源
      最近更新 更多