Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill right side of stringstream variable with '0' c++

Tags:

c++

I have the next code:

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()

and i hope the result:

2222100000

but only i get

22221

without zeros? what happened?

like image 843
user1310873 Avatar asked Jul 20 '12 19:07

user1310873


2 Answers

Use std::left to left justify the output

#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;
}

Output:

222200000
like image 51
Praetorian Avatar answered Nov 16 '22 15:11

Praetorian


manipulators are applied to the stream the same as input. For them to take effect they need to be applied first. For example here is how you would fill zeros on a string stream.

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

If you want to fill differently then simply add in a direction manipulator like std::left, std::right, etc.

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
like image 34
AJG85 Avatar answered Nov 16 '22 14:11

AJG85