4

I'm starting to work with Linux and GTK and ran in a strange problem. I am using sprintf() in my code to parse a float into a char array.

When parsing the number 1 into the string this resulted in "1.000000" but strangely after calling gtk_init() when I then do the sprintf it results in "1,000000". How does gtk_init() modify this behavior and how can I force the program to keep parsing it to "1.000000".

This is my small example program that reproduces the problem:

#include <gtk/gtk.h>

int main(int argc, char** argv)
{
    char cMessage[12];
    float fNumber = 1;
    sprintf(cMessage, "T:%f", fNumber);
    printf("%s\n", cMessage);

    gtk_init(&argc, &argv);

    sprintf(cMessage, "T:%f", fNumber);
    printf("%s\n", cMessage);

    return 0;
}

The output of this program is the following:

T:1.000000
T:1,000000
2
  • 3
    Seems like a locale issue. Does it help if you put setlocale(LC_ALL, "en_US.UTF-8"); as the first line in main? Commented Oct 1, 2018 at 12:57
  • Not your problem, but: char cMessage[12] in this code is an accident waiting to happen. You've got very little leeway in that buffer if the formatted string ends up slightly longer than you expect. I'd suggest (a) char cMessage[30], and/or (better) snprintf(cMessage, sizeof(cMessage), "T:%f", fNumber);. Commented Oct 1, 2018 at 14:13

1 Answer 1

7

This is related to your locale/language environment. Before calling gtk_init, you LOCALE variable must be set the the default value, C. gtk_init by default, sets the locale to whatever your desktop environment is set to.

To turn this behaviour off, you can use gtk_disable_setlocale.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.