将 int 转换为 C++ 中带有 2 位数字的字符串
Convert an int to a string with 2 digits in C++
我在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
我对这段代码的唯一问题是,对于 0x00
和 0x0a
之间的任何 led_pwm
值,它会转换为 led_pwm_string
的一位数。这给以后的我带来了问题。
我希望,在各种可能的情况下,led_pwm_string
始终包含一个 2 位字符串。因此,如果led_pwm
是0x01
(例如),那么led_pwm_string
将被01
,而不仅仅是1
。
尝试:
ostr << std::hex << std::setw(2) << std::setfill('0') << led_pwm;
您可能需要#include <iomanip>
。
相关文章:
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值