用c++格式化索引
Formatting index in c++
我有一个for循环,我想将索引I(取值1-1000)格式化为0001-1000。我遇到了使用printf和cout格式化索引的解决方案,但我想为字符串名称这样做。我正在尝试类似的东西,但它不起作用:
for(int i=0; i<1000; i++){
string num2string = setfill('0') +setw(4) + i;
}
如何将setfill和setw转换为字符串对象??
setfill
和setw
是IO操纵器,必须使用<<
运算符应用于IO流。在您的情况下,您需要创建一个stringstream
来将流操作重定向到字符串。例如,打印0013
:
#include <iostream>
#include <sstream>
#include <iomanip>
std::string num2string(int n)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(4) << n;
return ss.str();
}
int main()
{
std::cout << num2string(13);
}
如果您想获得字符串作为结果,并且仍然使用setfill和setw:,则可以使用字符串流
for(int i=0; i<1000; i++){
std::ostringstream stringStream;
stringStream << std::setfill ('0') << std::setw (4) << i;
std::string num2string = stringStream.str();
}
请改用std::ostringstream
。std::string
本身没有太多格式化帮助程序。它是ostream
(类似于cout
是其实例):
std::ostringstream ss; // Note: not creating it everytime to repeat less work
ss << setfill('0');
for(int i=0; i<1000; i++) {
ss.str("");
ss << setw(4) << i;
string num2string = ss.str();
}
不幸的是,对于您的情况,setw
没有保持在stringstream
的状态,因此您每次都必须设置它。
第三方的替代方案是boost格式库:
#include <boost/format.hpp>
....
string num2string = boost::format("%04d")%i;
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 查找最接近的大于当前数字的数字的索引
- C++格式化输出问题
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- D3D11-将混合权重和索引传递到顶点着色器
- 格式化浮点值:返回默认值
- 将转换字符键入 int 以用作向量C++的索引
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何为圆环创建索引
- 在子集化后将包含索引号的列表列表映射到标准索引序列
- 查找字符在两个索引之间出现的次数
- 自动格式化程序> >更改为>>
- 用c++格式化索引