How to do an "equivalence" of IO in Java and C ++?

9

I made the following code in C ++:

#include <iostream>
template <typename type> class Foo
{
    public:
    Foo(type FooTest)
    {
        std::cout << "Foo " << FooTest;
    }
};

int main
{
    new Foo<double>(10.0);
}

Output: "Foo 10".

Java: (MainClass.java)

public class MainClass
{

        public static void main(String[] args)
        {
            new Foo<Double>(10.0);
        }
}

    class Foo<type>
    {
        public Foo(type FooTest)
        {
            System.out.print("Foo ");
            System.out.print(FooTest);
        }
    }

Output: "Foo 10.0".

This, just one case to demonstrate what happens, the output is different in both cases for double. How can I match them (Java = 10 and C ++ = 10.0)?

    
asked by anonymous 01.03.2014 / 03:25

2 answers

7

The default formatting in C ++ tries to act intelligently and discards zeros from decimal places that do not interfere with value, if you put 1.1 on both, you will see that the output will be the same.

To have a fixed precision formatting you can use the std::setprecision handler along with std::fixed .

    
01.03.2014 / 04:00
1

You can use printf :)

C / C ++

printf("Foo %.01f", fooTest);

Java

System.out.printf("Foo %.01f", fooTest);

Of course this is a specific case for double , since you are using a generic type it would be interesting to declare a common interface on both systems (or else declare wrappers < in> overlapping the operator<< in C ++ and the toString method in Java), so that each type knows how to "print".

    
01.03.2014 / 03:57