1

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?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rok
  • 787
  • 9
  • 17
  • 4
    "it didn't work out", what exactly did you try? Fact is, it works, provided you do it right. Please provide a minimal example while you're at it. Oh, and please explain how Qt (did you mean that with "QT"?) is related to your question. – Ulrich Eckhardt Oct 24 '15 at 22:14
  • 2
    If you use fscanf, then that's not QT. – Christopher Oezbek Oct 24 '15 at 22:14
  • 1
    Question doesn't seem to have anything to do with C++ or Qt. – MrEricSir Oct 24 '15 at 22:28
  • The thing why I added QT in the name is because if I try the same example and compile it with the default "C++ Single File" build system in Sublime Text 3 it works with the dots but doesn't work with the commas. Its weird and I'm not even setting any locales. – Rok Oct 25 '15 at 06:13
  • Hmm, just noticed this is `scanf` not `printf`. Same solution, but a better dupe target would be [How do i read a float value when this value have comma instead of dot?](https://stackoverflow.com/questions/20007872/how-do-i-read-a-float-value-when-this-value-have-comma-instead-of-dot) or [How to parse numbers like "3.14" with scanf when locale expects "3,14"](https://stackoverflow.com/questions/13919817/how-to-parse-numbers-like-3-14-with-scanf-when-locale-expects-3-14). – miken32 Jun 10 '22 at 17:54

1 Answers1

3

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • I was adding the line to the wrong spot in my code and instead of `LC_ALL` I had `LC_NUMERIC`. I had it in the `main.cpp` file instead of the actual function where I use `fscanf`. Thank you. – Rok Oct 25 '15 at 06:26