Qt6 topics merged with General

Qt-Application and printf/scanf of floats

  • I live in germany and therefore I prefer german environment, which includes the environment variable LANG set to a value de_DE.UTF-8. And of course Linux.

    Currently I am writing a Gui interface for some library which uses printf() to write data and scanf to read data. I try not to change anything within that library, it strongly shall stay unchanged.

    Now there seems to be a little problem, since inside Qt a call to setlocale() is done and that changes the behaviour of printf/scanf to use the german style "," as a decimal point, instead of the C-style ".".

    A minimalistic example program to show that change:

    #include <QtWidgets/qapplication.h>
    #include <stdio.h>
    int main(int argc, char **argv) {
       float f;
       printf("Before QApp %f ", 3.14);
       sscanf("3.14", "%f", &f);
       printf(" ... reading 3.14 as %f\n", f);
       QApplication a(argc, argv);
       printf("After QApp %f ", 3.14);
       sscanf("3.14", "%f", &f);
       printf(" ... reading 3.14 as %f\n", f);
       return 0;

    I compiled this small program with
    g++ -fPIC -I /usr/include/qt5 main.c -lQt5Core -lQt5Widgets
    and got the following:

    $ ./a.out 
    Before QApp 3.140000  ... reading 3.14 as 3.140000
    After QApp 3,140000  ... reading 3.14 as 3,000000

    I can easily fix that change of behaviour by doing a call setlocale(LC_ALL, "C"); right after creating that instance of QApplication. So reading/writing of various files in that library works again.

    But I still have one question: Does that call of setlocale change any behaviour of the visual part of my Application, meaning: does Qt behave different? Does any Widget depend on it? Or with other words: What is that magic really good reason causing that change of the behavior of printf/scanf which is obviously caused by code inside Qt?

    I found one discussion on the net, but somehow it does not ring any bell :-( http://stackoverflow.com/questions/25661295/why-does-qcoreapplication-call-setlocalelc-all-by-default-on-unix-linux

Log in to reply