C programming + GTK: Add two numbers.

Iniciado por GisiNA, 21 Junio 2013, 19:25 PM

0 Miembros y 1 Visitante están viendo este tema.

GisiNA

I'm trying to write a program to add two numbers with a graphical interface written in GTK.
My problem is that it fails to recognize the values ​​entered in the text-box, as numbers.

I searched a long time through google, but I have not found an answer. I have found similar problems, but without an appropriate response.

I hope my query is not outside the margins of the forum.

Can anybody help me to solve the problem that I have in the "action_button function"?

Here my program:


#include <gtk/gtk.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
#define Length1 3
#define Length2 5
 
GtkWidget *n1, *n2;
GtkWidget *label_sum;

//The Callback funktion. Here is the problem:
void action_button(GtkButton *button, gpointer data){
 
    char result_sum;
    float float_n1, float_n2, sum;
 
    float_n1    = (float)(gtk_entry_get_text(GTK_ENTRY(n1)));
    float_n2    = (float)(gtk_entry_get_text(GTK_ENTRY(n2)));
 
    sum = float_n1 + float_n2;
 
    printf(result_sum, "HA - %d", sum);
    gtk_label_set_label((GtkLabel *)label_sum, result_sum);
 
}


//The Interface part. The problem is not here. 
int main(int argc, char *argv[]){
 
     GtkWidget *window, *descr[15], *layout, *button;
 
     gtk_init_check(&argc, &argv);
 
    //Build window.
     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
     g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
     gtk_window_set_title(GTK_WINDOW(window), "Calculo de Nota");
     gtk_container_set_border_width(GTK_CONTAINER(window), 0);
     gtk_window_set_default_size(GTK_WINDOW(window), 300, 300);
 
    //Build layout.
     layout = gtk_layout_new(NULL, NULL);
 
    //Build labels, one title and two indicator.
     descr[0] = gtk_label_new("Add two numbers");
     descr[1] = gtk_label_new("Number 1: ");
     descr[2] = gtk_label_new("Number 2: ");
     label_sum  = gtk_label_new("");
 
    //Build text fields.
     n1     = gtk_entry_new();
     n2     = gtk_entry_new();
 
     gtk_entry_set_max_length(GTK_ENTRY(n1), Length1);
     gtk_entry_set_max_length(GTK_ENTRY(n2), Length1);
 
     gtk_entry_set_width_chars(GTK_ENTRY(n1), Length2);
     gtk_entry_set_width_chars(GTK_ENTRY(n2), Length2);
 
    //Build the button.
     button = gtk_button_new_with_label("Calcular");
     //g_signal_connect(button, "clicked", G_CALLBACK(action_button), NULL);
 
    //Insert the widgets into the layout.
     gtk_layout_put(GTK_LAYOUT(layout), descr[0], 10, 10);
     gtk_layout_put(GTK_LAYOUT(layout), descr[1], 10, 50);
     gtk_layout_put(GTK_LAYOUT(layout), descr[2], 10, 90);
     gtk_layout_put(GTK_LAYOUT(layout), n1, 180, 50);
     gtk_layout_put(GTK_LAYOUT(layout), n2, 180, 90);
     gtk_layout_put(GTK_LAYOUT(layout), button, 10, 200);
     gtk_layout_put(GTK_LAYOUT(layout), label_sum, 90, 205);//Widget label for printing result.
 
    //Put the layout into the window.
     gtk_container_add(GTK_CONTAINER(window), layout);
 
     gtk_widget_show_all(window);
     gtk_main();
 
return 0;
}

I get the following error:
"prog.c: In function 'action_button':
prog.c:17:5: error: pointer value used where a floating point value was expected
prog.c:18:5: error: pointer value used where a floating point value was expected
prog.c:22:5: warning: passing argument 1 of 'printf' makes pointer from integer without a cast [enabled by default]"


What I'm doing wrong?
Thanks for any help.
(Sorry for my bad English. I'm not native speaker.).
Gisi

(Answers could be in Spanish, English or German)

0xDani

Most forums are in English, so I wonder why are you posting here. And I don't think your English is bad, I think actually it would be better for you to ask in another forum, as you'd get more answers to your problem.
I keep searching for something that I never seem to find, but maybe I won't, because I left it all behind!

I code for $$$
Hago trabajos en C/C++
Contactar por PM

avesudra

#2
Hi GisiNa, the problem with your code is that gtk_entry_get_text() returns a string and the compiler warns you that the conversion: string(which is actually a const gchar *) to float is not possible. The solution is to convert the number in the string to float using the sscanf function, so replace this:

float_n1    = (float)(gtk_entry_get_text(GTK_ENTRY(n1)));
float_n2    = (float)(gtk_entry_get_text(GTK_ENTRY(n2)));

By this:

sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);


Gracias a 0xDani por la ayuda con el inglés  ;D
Thanks to 0xDani for the help with the English  ;D
Regístrate en

GisiNA

#3
Thanks for your answer avesudra! Right now I try the suggestion. Soon as I have scored results leave a message. I have no problems if your answers are in English, Spanish or German.

Avesudra, gracias por tu respuesta! Ahora mismo intentaré las sugerencia. Apenas tenga resultados dejaré anotado un aviso. ¡No tengo problemas si me respondes en Inglés, Español o Alemán!  :D

¡Saludos!




Cita de: 0xDani en 21 Junio 2013, 19:59 PM
Most forums are in English, so I wonder why are you posting here. And I don't think your English is bad, I think actually it would be better for you to ask in another forum, as you'd get more answers to your problem.


:-* Yes, if I know. The reason is that of all the forums to join, this proved to be the simplest, and it is in my native language, Spanish. It may not be the most appropriate ... If I can not find an answer here, I will subscribe a forum in English. Thank you for considering my English not so bad.

maxim_o

Si eres española nativa, por que no posteas en español?

GisiNA

Cita de: avesudra en 21 Junio 2013, 20:24 PM
Hi GisiNa, the problem with your code is that gtk_entry_get_text() returns a string and the compiler warns you that the conversion: string(which is actually a const gchar *) to float is not possible. The solution is to convert the number in the string to float using the sscanf function, so replace this:

float_n1    = (float)(gtk_entry_get_text(GTK_ENTRY(n1)));
float_n2    = (float)(gtk_entry_get_text(GTK_ENTRY(n2)));

By this:

sscanf(gtk_entry_get_text(GTK_ENTRY(n1),"%f", &float_n1);
sscanf(gtk_entry_get_text(GTK_ENTRY(n2),"%f", &float_n2);


Gracias a 0xDani por la ayuda con el inglés  ;D
Thanks to 0xDani for the help with the English  ;D

Hola avesudra!

Lamentablemente me arroja errores similares.

"In function 'action_button':
error: too many arguments to function 'gtk_entry_get_text'
error: too few arguments to function 'sscanf'
warning: passing argument 1 of 'printf' makes pointer from integer without a cast [enabled by default]"

O sea, considera que gtk_entry_get_text contiene demasiados argumentos y de otra parte, a sscanf le estarían faltando parámetros. Y finalmente prevalece el problema de conversión entre puntero y número.

Hasta ahora me ha sido imposible conseguir la conversión de lo que se ingresa en un campo de texto (un char) en número...

¿Tendrás alguna idea...?

¡Gracias!

avesudra

#6
Cita de: GisiNA en 22 Junio 2013, 12:53 PM
Hola avesudra!

Lamentablemente me arroja errores similares.

"In function 'action_button':
error: too many arguments to function 'gtk_entry_get_text'
error: too few arguments to function 'sscanf'
warning: passing argument 1 of 'printf' makes pointer from integer without a cast [enabled by default]"

O sea, considera que gtk_entry_get_text contiene demasiados argumentos y de otra parte, a sscanf le estarían faltando parámetros. Y finalmente prevalece el problema de conversión entre puntero y número.

Hasta ahora me ha sido imposible conseguir la conversión de lo que se ingresa en un campo de texto (un char) en número...

¿Tendrás alguna idea...?

¡Gracias!
Ups, sorry for the mistake I forgot two parenthesis:
Ups, perdón por el error, olvidé dos paréntesis:
sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);

This not have much sense:
Esto no tiene mucho sentido:

   //"%d"? o %f ...
  // Que esta haciendo result_sum aqui?
  // What is doing result_sum here?
   printf(result_sum, "HA - %d", sum);

The printf function is defined so:
La función printf está definida así:
int printf ( const char * format, ... );
So this should be run(the mistakes are in the comments):
Así que esto debería funcionar (los errores están en los comentarios):
void action_button(GtkButton *button, gpointer data)
{
   //You have to declare an array for show this then... not only a char.
   //Tienes que declarar un array para mostrarlo después, no solamente un caracter.
   char result_sum[100];
   float float_n1, float_n2, sum;

   sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
   sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);

   sum = float_n1 + float_n2;
   //You had confused printf with sprintf
   // Habías confundido printf con sprintf
   sprintf(result_sum,"HA - %f", sum);
   gtk_label_set_label((GtkLabel *)label_sum, result_sum);
}
Regístrate en

GisiNA

Cita de: avesudra en 22 Junio 2013, 13:04 PM
Ups, sorry for the mistake I forgot two parenthesis:
Ups, perdón por el error, olvidé dos paréntesis:
sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);

This not have much sense:
Esto no tiene mucho sentido:

   //"%d"? o %f ...
  // Que esta haciendo result_sum aqui?
  // What is doing result_sum here?
   printf(result_sum, "HA - %d", sum);

The printf function is defined so:
La función printf está definida así:
int printf ( const char * format, ... );
So this should be run(the mistakes are in the comments):
Así que esto debería funcionar (los errores están en los comentarios):
void action_button(GtkButton *button, gpointer data)
{
   //You have to declare an array for show this then... not only a char.
   //Tienes que declarar un array para mostrarlo después, no solamente un caracter.
   char result_sum[100];
   float float_n1, float_n2, sum;

   sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
   sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);

   sum = float_n1 + float_n2;
   //You had confused printf with sprintf
   // Habías confundido printf con sprintf
   sprintf(result_sum,"HA - %f", sum);
   gtk_label_set_label((GtkLabel *)label_sum, result_sum);
}


¡Hola avesudra!

¡Excelente! Ha funcionado perfectamente. Sinceramente muy pero muy agradecida y admirada. Yo soy nueva en programación con GTK y ésta duda me ha perseguido por ya casi dos meses... ¡Gracias!

Dejo acá el código completo para todos quienes tengan dudas similares. Sobre la base de la ayuda dada por avesudra, el código completo sin errores para que funcione la suma entre dos valores en C con GTK es:

(I leave here the complete code (without errors) for all who have similar doubts. Based on the help given by avesudra, the total code to operate the sum of two values ​​in C with GTK is:)



#include <gtk/gtk.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
     
#define Length1 3
#define Length2 5
     
GtkWidget *n1, *n2;
GtkWidget *label_sum;
     
void action_button(GtkButton *button, gpointer data){
     
    char result_sum[100];
    float float_n1, float_n2, sum;
     
    //Transforming strings to numbers of type float.
    sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
    sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);
     
    sum = float_n1 + float_n2; //Adding both numbers.                                                                                     

    sprintf(result_sum,"Result - %f", sum); //Passing the result of the sum to a variable.
    gtk_label_set_label((GtkLabel *)label_sum, result_sum);//Passing the result to label_sum for print  on the window.
     
}   
     
int main(int argc, char *argv[]){
     
     GtkWidget *window, *descr[15], *layout, *button;
     
     gtk_init_check(&argc, &argv);
     
    //Build window.
     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
     g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
     gtk_window_set_title(GTK_WINDOW(window), "Calculo de Nota");
     gtk_container_set_border_width(GTK_CONTAINER(window), 0);
     gtk_window_set_default_size(GTK_WINDOW(window), 300, 300);
     
    //Build layout.
     layout = gtk_layout_new(NULL, NULL);
     
    //Build labels, one title and two indicator.
     descr[0] = gtk_label_new("Add two numbers");
     descr[1] = gtk_label_new("Number 1: ");
     descr[2] = gtk_label_new("Number 2: ");
     label_sum  = gtk_label_new("Resultado.");
     
    //Build text fields.
     n1     = gtk_entry_new();
     n2     = gtk_entry_new();
     
     gtk_entry_set_max_length(GTK_ENTRY(n1), Length1);
     gtk_entry_set_max_length(GTK_ENTRY(n2), Length1);
     
     gtk_entry_set_width_chars(GTK_ENTRY(n1), Length2);
     gtk_entry_set_width_chars(GTK_ENTRY(n2), Length2);
     
    //Build the button.
     button = gtk_button_new_with_label("Calcular");
     g_signal_connect(button, "clicked", G_CALLBACK(action_button), NULL);
     
    //Insert the widgets into the layout.
     gtk_layout_put(GTK_LAYOUT(layout), descr[0], 10, 10);
     gtk_layout_put(GTK_LAYOUT(layout), descr[1], 10, 50);
     gtk_layout_put(GTK_LAYOUT(layout), descr[2], 10, 90);
     gtk_layout_put(GTK_LAYOUT(layout), n1, 180, 50);
     gtk_layout_put(GTK_LAYOUT(layout), n2, 180, 90);
     gtk_layout_put(GTK_LAYOUT(layout), button, 10, 200);
     gtk_layout_put(GTK_LAYOUT(layout), label_sum, 90, 205);//Widget label for printing result.
     
    //Put the layout into the window.
     gtk_container_add(GTK_CONTAINER(window), layout);
     
     gtk_widget_show_all(window);
     gtk_main();
     
return 0;
}