Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: GisiNA en 21 Junio 2013, 19:25 pm



Título: C programming + GTK: Add two numbers.
Publicado por: GisiNA en 21 Junio 2013, 19:25 pm
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)


Título: Re: C programming + GTK: Add two numbers.
Publicado por: 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.


Título: Re: C programming + GTK: Add two numbers.
Publicado por: 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:
Código
  1. float_n1    = (float)(gtk_entry_get_text(GTK_ENTRY(n1)));
  2. float_n2    = (float)(gtk_entry_get_text(GTK_ENTRY(n2)));
By this:
Código
  1. sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
  2. 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


Título: Re: C programming + GTK: Add two numbers.
Publicado por: GisiNA en 22 Junio 2013, 11:46 am
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!



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.


Título: Re: C programming + GTK: Add two numbers.
Publicado por: maxim_o en 22 Junio 2013, 12:08 pm
Si eres española nativa, por que no posteas en español?


Título: Re: C programming + GTK: Add two numbers.
Publicado por: GisiNA en 22 Junio 2013, 12:53 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:
Código
  1. float_n1    = (float)(gtk_entry_get_text(GTK_ENTRY(n1)));
  2. float_n2    = (float)(gtk_entry_get_text(GTK_ENTRY(n2)));
By this:
Código
  1. sscanf(gtk_entry_get_text(GTK_ENTRY(n1),"%f", &float_n1);
  2. 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!


Título: Re: C programming + GTK: Add two numbers.
Publicado por: avesudra en 22 Junio 2013, 13:04 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:
Código
  1. sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
  2. sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);
This not have much sense:
Esto no tiene mucho sentido:
Código
  1.    //"%d"? o %f ...
  2.   // Que esta haciendo result_sum aqui?
  3.   // What is doing result_sum here?
  4.    printf(result_sum, "HA - %d", sum);
The printf function is defined so:
La función printf está definida así:
Código
  1. 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):
Código
  1. void action_button(GtkButton *button, gpointer data)
  2. {
  3.    //You have to declare an array for show this then... not only a char.
  4.    //Tienes que declarar un array para mostrarlo después, no solamente un caracter.
  5.    char result_sum[100];
  6.    float float_n1, float_n2, sum;
  7.  
  8.    sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
  9.    sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);
  10.  
  11.    sum = float_n1 + float_n2;
  12.    //You had confused printf with sprintf
  13.    // Habías confundido printf con sprintf
  14.    sprintf(result_sum,"HA - %f", sum);
  15.    gtk_label_set_label((GtkLabel *)label_sum, result_sum);
  16. }


Título: Re: C programming + GTK: Add two numbers.
Publicado por: GisiNA en 22 Junio 2013, 14:46 pm
Ups, sorry for the mistake I forgot two parenthesis:
Ups, perdón por el error, olvidé dos paréntesis:
Código
  1. sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
  2. sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);
This not have much sense:
Esto no tiene mucho sentido:
Código
  1.    //"%d"? o %f ...
  2.   // Que esta haciendo result_sum aqui?
  3.   // What is doing result_sum here?
  4.    printf(result_sum, "HA - %d", sum);
The printf function is defined so:
La función printf está definida así:
Código
  1. 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):
Código
  1. void action_button(GtkButton *button, gpointer data)
  2. {
  3.    //You have to declare an array for show this then... not only a char.
  4.    //Tienes que declarar un array para mostrarlo después, no solamente un caracter.
  5.    char result_sum[100];
  6.    float float_n1, float_n2, sum;
  7.  
  8.    sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
  9.    sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);
  10.  
  11.    sum = float_n1 + float_n2;
  12.    //You had confused printf with sprintf
  13.    // Habías confundido printf con sprintf
  14.    sprintf(result_sum,"HA - %f", sum);
  15.    gtk_label_set_label((GtkLabel *)label_sum, result_sum);
  16. }

¡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:)


Código
  1. #include <gtk/gtk.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5.  
  6. #define Length1 3
  7. #define Length2 5
  8.  
  9. GtkWidget *n1, *n2;
  10. GtkWidget *label_sum;
  11.  
  12. void action_button(GtkButton *button, gpointer data){
  13.  
  14.    char result_sum[100];
  15.    float float_n1, float_n2, sum;
  16.  
  17.    //Transforming strings to numbers of type float.
  18.    sscanf(gtk_entry_get_text(GTK_ENTRY(n1)),"%f", &float_n1);
  19.    sscanf(gtk_entry_get_text(GTK_ENTRY(n2)),"%f", &float_n2);
  20.  
  21.    sum = float_n1 + float_n2; //Adding both numbers.                                                                                    
  22.  
  23.    sprintf(result_sum,"Result - %f", sum); //Passing the result of the sum to a variable.
  24.    gtk_label_set_label((GtkLabel *)label_sum, result_sum);//Passing the result to label_sum for print  on the window.
  25.  
  26. }    
  27.  
  28. int main(int argc, char *argv[]){
  29.  
  30.     GtkWidget *window, *descr[15], *layout, *button;
  31.  
  32.     gtk_init_check(&argc, &argv);
  33.  
  34.    //Build window.
  35.     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  36.     g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
  37.     gtk_window_set_title(GTK_WINDOW(window), "Calculo de Nota");
  38.     gtk_container_set_border_width(GTK_CONTAINER(window), 0);
  39.     gtk_window_set_default_size(GTK_WINDOW(window), 300, 300);
  40.  
  41.    //Build layout.
  42.     layout = gtk_layout_new(NULL, NULL);
  43.  
  44.    //Build labels, one title and two indicator.
  45.     descr[0] = gtk_label_new("Add two numbers");
  46.     descr[1] = gtk_label_new("Number 1: ");
  47.     descr[2] = gtk_label_new("Number 2: ");
  48.     label_sum  = gtk_label_new("Resultado.");
  49.  
  50.    //Build text fields.
  51.     n1     = gtk_entry_new();
  52.     n2     = gtk_entry_new();
  53.  
  54.     gtk_entry_set_max_length(GTK_ENTRY(n1), Length1);
  55.     gtk_entry_set_max_length(GTK_ENTRY(n2), Length1);
  56.  
  57.     gtk_entry_set_width_chars(GTK_ENTRY(n1), Length2);
  58.     gtk_entry_set_width_chars(GTK_ENTRY(n2), Length2);
  59.  
  60.    //Build the button.
  61.     button = gtk_button_new_with_label("Calcular");
  62.     g_signal_connect(button, "clicked", G_CALLBACK(action_button), NULL);
  63.  
  64.    //Insert the widgets into the layout.
  65.     gtk_layout_put(GTK_LAYOUT(layout), descr[0], 10, 10);
  66.     gtk_layout_put(GTK_LAYOUT(layout), descr[1], 10, 50);
  67.     gtk_layout_put(GTK_LAYOUT(layout), descr[2], 10, 90);
  68.     gtk_layout_put(GTK_LAYOUT(layout), n1, 180, 50);
  69.     gtk_layout_put(GTK_LAYOUT(layout), n2, 180, 90);
  70.     gtk_layout_put(GTK_LAYOUT(layout), button, 10, 200);
  71.     gtk_layout_put(GTK_LAYOUT(layout), label_sum, 90, 205);//Widget label for printing result.
  72.  
  73.    //Put the layout into the window.
  74.     gtk_container_add(GTK_CONTAINER(window), layout);
  75.  
  76.     gtk_widget_show_all(window);
  77.     gtk_main();
  78.  
  79. return 0;
  80. }
  81.