2

I created a qt application with qt creator, the code is like,

#include "mainwindow.h"
#include <QDebug>
#include <QApplication>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  double before = atof("3.1");
  double x;
  sscanf("3.1", "%lf", &x);
  QApplication a(argc, argv);
  double after = atof("3.1");
  double y;
  sscanf("3.1", "%lf", &y);
  MainWindow w;
  w.show();
  qDebug() <<  before;
  qDebug() <<  after;
  qDebug() <<  x;
  qDebug() <<  y;
  return a.exec();
}

the output is

3.1
3
3.1
3

That means sscanf and atof truncates fractional parts after "QApplication a(argc, argv);". The problem only occurs in Qt5.3 under Linux Mint 17. I tested the same program in windows 8 and Mac OS 10.9, they don't have the same problem. Is it a bug in Linux Qt5.3 or it has something to do with linux c library?

The complete code can be accessed here

user2621037
  • 326
  • 1
  • 3
  • 13

1 Answers1

2

See QCoreApplication documentation:

On Unix/Linux Qt is configured to use the system locale settings by default. This can cause a conflict when using POSIX functions, for instance, when converting between data types such as floats and strings, since the notation may differ between locales. To get around this problem, call the POSIX function setlocale(LC_NUMERIC,"C") right after initializing QApplication or QCoreApplication to reset the locale that is used for number formatting to "C"-locale.

I can reproduce your problem and the following code fixes it for me:

QApplication a(argc, argv);
setlocale(LC_NUMERIC,"C");
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
  • 1
    To be more specific, in some locales decimal point is *not* `.` (it might be `,`). And both `scanf` and `atof` stop scanning at first illegal character, thus getting only `3` when the decimal point char in string is wrong for the locale. – hyde Jun 30 '14 at 20:59