C++ c+中的格式索引+;

C++ c+中的格式索引+;,c++,indexing,format,C++,Indexing,Format,我有一个for循环,我想将索引I(取值1-1000)格式化为0001-1000。我遇到了使用printf和cout格式化索引的解决方案,但我想为字符串名这样做。我正在尝试类似的方法,但不起作用: for(int i=0; i<1000; i++){ string num2string = setfill('0') +setw(4) + i; } for(int i=0;isetfill和setw必须使用setfill应用于IO流,而setw必须使用应用于IO

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

   for(int i=0; i<1000; i++){

      string num2string = setfill('0') +setw(4) + i; 
   } 

for(int i=0;i
setfill
setw
必须使用
setfill
应用于IO流,而
setw
必须使用
应用于IO流。如果您希望获得字符串,并且仍然使用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();
}

for(int i=0;i如果希望得到一个字符串,并且仍然使用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();
}

for(int i=0;i改用
std::ostringstream
std::string
本身没有太多格式帮助程序。它是一个
ostream
(如
cout
就是其中的一个实例):


请改用
std::ostringstream
std::string
本身没有太多格式帮助程序。它是一个
ostream
(如
cout
就是其中的一个实例):


@ Felees <代码> IOMANIP需要<代码> >代码>和>代码> STD::SEtW商店标准代码> @ FELRES,在标准C++中,必须包含头。例如,在G++ 4.6上,删除<代码>包含编译错误>编译器>抱怨:<代码> SETPAST/<代码>和<代码> SEtW商店< /C> >不是代码> STD/C的成员。ODE>@ Felees <代码> IOMANIP需要<代码> >代码>和>代码> STD::SEtW商店标准代码> @ FELRES,在标准C++中,必须包括头。例如,在G++ 4.6上,删除<代码>包含编译错误>编译器>抱怨:<代码> SETPAST/<代码>和<代码> SEtW商店< /代码>不是<代码> s的成员。td
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();
}
#include <boost/format.hpp>
....

    string num2string = boost::format("%04d")%i;