formatting double output

My program involves getting double input, performing some calculations, and then displaying the double results along with the original input. I have the whole thing set to cout << fixed << showpoint; and I am using setprecision(2) to make the results show to 2 decimal points. My problem is that I want the displayed output of the initial input to look exactly like the input, e.g. if the input was 4 I want it to output "4" not "4.00000...", or if it was 3.456 output "3.456". How do I do this?
> I want the displayed output of the initial input to look exactly like the input

Get the input as a std::string
For calculations, convert the string to a double.
For displaying of the input, display the original string.

http://liveworkspace.org/code/2SV6g8$0
Is that the only easy way to do it? I don't think we've covered strings in class yet, so I'd feel a bit weird using it for an assignment...
> Is that the only easy way to do it?

How else could we do it?
The same number can be specified in a variety of formats.

1
2
3
double a = +1.2345e+2, b = 123.45, c = +123.45, d = 12345e-2, e = 000.012345e4 ;
// this will display 123.45 five times
std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << e << '\n' ;



> I don't think we've covered strings in class yet.

That shouldn't prevent you from using it.

Though it is not ideal, we could also use a c-style string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>

int main()
{

    char cstr[128] = "" ;
    std::cin.getline( cstr, sizeof(cstr) ) ;

    errno = 0 ;
    double v = std::strtod( cstr, nullptr ) ;
    if( errno == 0 )
    {
        // success, use v
        std::cout << cstr << " => " << v << '\n' ;
    }
    else
    {
        // error in convertion
        std::cerr << cstr << " is not a number\n" ;
    }
}
Topic archived. No new replies allowed.