fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <sstream>
  4. #include <vector>
  5.  
  6. int main()
  7. {
  8. std::vector<double> numbers {
  9. 3.141516, 1.01, 200.78901, 0.12345, 9.99999
  10. };
  11.  
  12. for (auto x : numbers)
  13. {
  14. // "print" the number
  15. std::stringstream ss;
  16. ss << std::fixed << std::setprecision(4) << x;
  17.  
  18. // remove the unwanted zeroes
  19. std::string result{ss.str()};
  20. while (result.back() == '0')
  21. result.pop_back();
  22.  
  23. // remove the separator if needed
  24. if (result.back() == '.')
  25. result.pop_back();
  26.  
  27. std::cout << result << '\n';
  28. }
  29.  
  30. std::cout << "\nJustified:\n";
  31. for (auto x : numbers)
  32. {
  33. // "print" the number
  34. std::stringstream ss;
  35. ss << std::fixed << std::setprecision(4) << std::setw(15) << x;
  36.  
  37. // remove the unwanted zeroes
  38. std::string result{ss.str()};
  39. auto it = result.rbegin();
  40. while (*it == '0')
  41. *it++ = ' ';
  42.  
  43. // remove the separator if needed
  44. if (*it == '.')
  45. *it = ' ';
  46.  
  47. std::cout << result << '\n';
  48. }
  49. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
3.1415
1.01
200.789
0.1235
10

Justified:
         3.1415
         1.01  
       200.789 
         0.1235
        10