64-bit integers and printf/scanf

eesti keeles | по-русски

Information for C users: input and output of 64-bit integers is slightly different between Windows and Linux.

On Linux (on the grading server) GCC uses the implemantations of printf and scanf from the GNU library glibc where the format string for 64-bit signed integers is %Ld or %lld and the format string for 64-bit unsigned integers is %Lu or %llu.

On Windows (in most computer labs) GCC/MinGW uses the implementations of printf and scanf from the Microsoft library MSVCRT.DLL where the format string for 64-bit signed integers is %I64d and the format string for 64-bit unsigned integers is %I64u.

For your solution to work correctly in both environments, it's best to write it as in the following example:

    #include <stdio.h>

    #ifdef _WIN32
        /* format strings for Windows */
        #define LONGLONG "%I64d"
        #define ULONGLONG "%I64u"
    #else
        /* format strings for Linux */
        #define LONGLONG "%Ld"
        #define ULONGLONG "%Lu"
    #endif

    int main() {
        long long a;
        int b;
        long c;
        unsigned long long d;
        double e;

        /* reading a 64-bit integer alone */
        scanf(LONGLONG, &a);
        /* reading a 64-bit integer among others */
        scanf("%d%ld" ULONGLONG "%lf", &b, &c, &d, &e);
        /* writing a 64-bit integer alone */
        printf(LONGLONG "\n", a);
        /* writing a 64-bit integer among others*/
        printf("%d %ld " ULONGLONG " %lf\n", b, c, d, e);

        return 0;
    }

The above applies also to using printf and scanf in C++ code, but does not affect the use of the streams library in C++ (the cin, cout, and cerr objects and the ifstream and ofstream classes).

The input and output operations of Pascal, Java, and Python have no difference between Windows and Linux.

Lehekülg viimati muudetud December 04, 2014, at 03:09 AM