C++

2020-05-05 04:37发布

问题:

I'm reading a file in c++ where floating point numbers (%f) have a dot instead of comma.

Each line in the file has 3 numbers like that

1.000 -1.000 0.000

for example.

My app does not want to read the number past the dot, so If I do

fscanf(file, "%f %f %f\n", &x, &y, &z );

for example x is set to 1, everything else is left on 0 because it only reads to the first dot.

I've already read somewhere that I should change the locale using setlocale or something similar but it didn't work out.

Could someone please explain how to do it properly or if there is another way?


EDIT: I removed "QT" from the title. First it was there because I thought that maybe QT has some special settings or something for locales. It's weird that my ST3 default C++ Single File build system has the locale already set to use dots instead of commas, but I had to set it in QT. Does every compiler have their own default locale setting?

回答1:

You can add the line

setlocale(LC_ALL, "C"); 

before the call to fscanf. Make sure to add

#include <locale.h>

to be able to call setlocale.

More on setlocale can be seen at http://en.cppreference.com/w/c/locale/setlocale.



标签: c++ locale comma