#include <iostream>
using namespace std;
int main()
{
double B = 2006.008;
printf(".2f", B);
return 0;
}
Output:
2006.01
with blank spaces in the beginning
I want to replace those white spaces with underscores(_). Is there any syntax in print or any direct method to do that?
My desired output:
_______ 2006.01
CodePudding user response:
With std::format
(C 20), you might do:
std::format("{:_>15.2}", B);
CodePudding user response:
or any direct method to do that?
One solution is to use the iomanip manipulators:
#include <iostream>
#include <iomanip>
int main()
{
double B = 2006.008;
printf(".2f\n", B); // Original
std::cout
<< std::setfill('_') // The fill character
<< std::right // right justify
<< std::setw(15) // field width
<< std::fixed // fixed precision
<< std::setprecision(2) // 2 decimals
<< B;
}
Output:
2006.01
________2006.01
CodePudding user response:
As in the comments suggested you can write a function for this, but not with printf().
#include <algorithm>
#include <iostream>
std::string formatNumber(double number)
{
char buffer[15 1 2];
sprintf(buffer, ".2f", number);
std::string s(buffer);
std::replace(s.begin(), s.end(), ' ', '_');
return s;
}
int main()
{
double B = 2006.008;
auto toPrint = formatNumber(B);
std::cout << toPrint << std::endl;
return 0;
}