Question

how can we add a number of type gint to a TextBuffer in gtk+3? gtk_text_buffer_set_text has argument of type gchar but I want to set integer of type gint

Was it helpful?

Solution 2

You cannot show an integer value directly. You must first format the integer value in a character buffer and set this as the text

GtkTextBuffer *textbuf;
char cbuf[15];
int n, v;
v = 738;
n = sprintf(cbuf, "%d", v);
gtk_text_buffer_set_text(textbuf, cbuf, n);

OTHER TIPS

When doing I/O in C, you generally use strings. Since this is a form of I/O, it's to be expected that you need to format the number into a string first.

This is also nice since formatting a number into a string can be done many ways (different bases, number of digits, padding, and so on) so keeping this on the application side means the GTK+ widget doesn't have to know all that stuff.

The glib string utility functions API has a bunch of functions for dealing with strings. The most relevant here is probably g_snprintf():

void number_to_buffer(GtkTextBuffer *textbuf, int number)
{
  char buf[32];

  const gint len = g_snprintf(buf, sizeof buf, "%d", number);
  gtk_text_buffer_set_text(textbuf, buf, len);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top