Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用';0';c++;_C++ - Fatal编程技术网

C++ 用';0';c++;

C++ 用';0';c++;,c++,C++,我有下一个代码: ofstream dataIndex; dataIndex.open("file"); index="2222"; std::stringstream sstr1; sstr1<<index<<'1'; sstr1<<setfill('0')<<setw(index.length()-9); string index1= sstr1.str(); dataIndex<<index1; dataIndex.close

我有下一个代码:

ofstream dataIndex;
dataIndex.open("file");

index="2222";
std::stringstream sstr1;
sstr1<<index<<'1';
sstr1<<setfill('0')<<setw(index.length()-9);
string index1= sstr1.str();
dataIndex<<index1;

dataIndex.close()
但只有我能

22221
没有零?发生了什么?

调用setw()操纵器时使用了负数(索引字符串的长度仅为4)。这可能是罪魁祸首。

用于左对齐输出

#include <iostream>
#include <string>
#include <iomanip>

int main() 
{
  std::string s( "2222" );

  std::cout << std::setw(9) 
            << std::setfill('0') 
            << std::left 
            << s 
            << std::endl;
}

操纵器与输入一样应用于流。要使它们生效,首先需要应用它们。例如,下面是如何在字符串流中填充零

std::string index("2222");
std::ostringstream sstr1;
sstr1 << std::setw(9) << std::setfill('0') << index << '1';
std::cout << sstr1.str(); // 0000022221

您正在将宽度设置为-5,即1。首先调用
setw
并使用正值。FWIW。这只是为了说明前面的几点。我会将输出更改为
sstr1.str()
。当然,只需在5分钟内将其组合起来。显然,您可能也希望计算出实际执行的任何操作的宽度,并将其全部封装在一个简单的函数中。
222200000
std::string index("2222");
std::ostringstream sstr1;
sstr1 << std::setw(9) << std::setfill('0') << index << '1';
std::cout << sstr1.str(); // 0000022221
std::string index("2222");
std::ostringstream sstr1;
sstr1 << index << std::setw(10-index.length()) << std::setfill('0') << std::left << '1';
std::cout << sstr1.str(); // 2222100000