用c++格式化索引

Formatting index in c++

本文关键字:索引 格式化 c++      更新时间:2023-10-16

我有一个for循环,我想将索引I(取值1-1000)格式化为0001-1000。我遇到了使用printf和cout格式化索引的解决方案,但我想为字符串名称这样做。我正在尝试类似的东西,但它不起作用:

   for(int i=0; i<1000; i++){
      string num2string = setfill('0') +setw(4) + i; 
   } 

如何将setfill和setw转换为字符串对象??

setfillsetw是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::ostringstreamstd::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;