elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Security Series.XSS. [Cross Site Scripting]


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Poner separador de miles a la hora de mostrar resultado en pantalla
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Poner separador de miles a la hora de mostrar resultado en pantalla  (Leído 4,085 veces)
galapok11

Desconectado Desconectado

Mensajes: 7


Ver Perfil
Poner separador de miles a la hora de mostrar resultado en pantalla
« en: 11 Agosto 2016, 11:36 am »

Saludos programadores.
He terminado un programa y me gustaria saber como incluir los separadores de miles a la hora de mostrar dicho resultado en pantalla. He estado investigando en Internet pero lo poco que he visto/entendido no he conseguido aplicarlo.
Gracias por leerme, y mas aun al que me responda :)

Este es el programa, siento que este en ingles...
/*+-------------------------------------------------------------------+*/
/*| System and library header files.                                  |*/
/*+-------------------------------------------------------------------+*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/*+-------------------------------------------------------------------+*/
/*| Defines                                                           |*/
/*+-------------------------------------------------------------------+*/

//Maximum characters of the file cypher.txt
#define LIMIT_NAMES 6000

/*+-------------------------------------------------------------------+*/
/*| Structs & Definitions                                             |*/
/*+-------------------------------------------------------------------+*/

/*+-------------------------------------------------------------------+*/
/*| Global Variables                                                  |*/
/*+-------------------------------------------------------------------+*/

/*+-------------------------------------------------------------------+*/
/*| Static Variables                                                  |*/
/*+-------------------------------------------------------------------+*/

static char array_list_names[LIMIT_NAMES][50];
int ins_total_score = 0;


////Static variables for the time
static int ins_time_start;                  //Start time of NameLists
static int ins_time_stop;                  //Finish time of NameLists

/*+-------------------------------------------------------------------+*/
/*| Internal function prototypes.                                     |*/
/*+-------------------------------------------------------------------+*/

/*+-------------------------------------------------------------------+*/
/*| Explanation                                |*/
/*+-------------------------------------------------------------------+*/


//A 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order.
//
//Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
//For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.
//What is the total of all the name scores in the file?
//
//In order to sort the names, you will need to use qsort (http://www.cplusplus.com/reference/cstdlib/qsort/).
//It might be a bit tricky and difficult,
//i'll let you try alone if you want, but due to the pointer redirection you will need to apply in order to use the function, i'll gladly help you out - so don't hesitate to stop by and ask me.

/*+-------------------------------------------------------------------+*/
/*| Main control procedure.                                           |*/
/*+-------------------------------------------------------------------+*/

   //Function compare by default
   int m_compare (const void * vpp_a, const void * vpp_b)
      {
         return strcmp((char *) vpp_a, (char *) vpp_b);
         //return ( *(int*)a - *(int*)b );
      }
   //////////////////////////////////////////////

int main ()
{
     //Indicate time
   clock_t t_start, t_end;
   double secs;
   t_start = clock();
   //////////////////////////////////////////////////////////////////////////////////////
   


   //////////////////////////////////////////////////////////////////////////////////////
   //Procedure to count the words of the file names.txt and keep the array with all names
 
   //Open file to read it
   FILE *file_names;
   file_names = fopen("names.txt", "r+");
   
   //If the file is incorrect, indicate it and close the program
   if (file_names==NULL)
   {
      printf("File's content is incorrect.");
      system("pause");
      return -1;
   }
    // //Function to count the total names of the file
   // int ins_number_names = 0+1;
   //      while(!feof(file_names))
   //      {
   //            if(fgetc(file_names) == ',')
   //            {
   //                   ins_number_names++;
   //            }
   //      }
   //////Show the total number of names
   //printf("\nThe Number of names of the file names.txt is %d\n", ins_number_names);
   //system("PAUSE");      

   //Variable to keep the total number of names
   int ins_number_names = 0;

   //Start a while to know the number of names, and keep all names in one array
   while(!feof(file_names) && ins_number_names < LIMIT_NAMES)
   {
      //Initial lenght for every name
        int lenght_names = 0;
      //Other characters of the file, in this case, the commas ','
        char other_char;
      //Limit of characters of the names
        char limit_char_names[50];

      //Exclude the commas ',' and double quotation marks ' " " ' to can counting the names
        while((other_char = fgetc(file_names)) != ',' && !feof(file_names))
      {
            if(other_char == '\"'){
                continue;
            }
            else{
                limit_char_names[lenght_names] = other_char;
                lenght_names++;
            }
        }
        limit_char_names[lenght_names] = '\0';

      //Keep with strcpy the names in the array array_list_names
        strcpy(array_list_names[ins_number_names],limit_char_names);
        ins_number_names++;
   }

   //Close the file names.txt
   fclose(file_names);
   /////////////////////////////////////////////////////////////////////////////////////



   //Show the array with all names to check it
   /*   for(int i = 0; i < ins_number_names; i++)
         {
         printf("%s ",array_list_names);
         }*/
   
   printf("\nThe total number of names is: %i\n",ins_number_names);
   system("PAUSE");
   
   
   //Start the function to sort all names in alphabetical order
   qsort (array_list_names, ins_number_names, 50, m_compare);
   
   //Show the array sorted to check the function sort
   /*for(int i=0; i<ins_number_names;i++)
      {
      printf ("%s ",array_list_names);   
      }*/
      
   //Start with the operations to calculate the name score and total score
   
   //Assign to every word of every name a value which will be the position of the letter
   for(int i1=0; i1<ins_number_names;i1++)
   {
      //Variable to indicate the sum
      int ins_sum=0;
      //Variable ins_number_char_names to know the lenght of the name
      int ins_lenght_names = strlen(array_list_names[i1]);

      for(int i2=0; i2<ins_lenght_names; i2++)
         {
         //Calculate the score of every character
         ins_sum += array_list_names[i1][i2] - 'A' + 1;
         }
      
      //Calculate the values
      int ins_value = ins_sum * (i1+1);
      //Calculate the total score
      ins_total_score += ins_value;
   }

   //Show the total score os the file names.txt
   printf("The total score of all names is: %i\n", ins_total_score);
   system("pause");
   ////////////////////////////////////////////////////////////////////////////////////


   //Show time
   t_end = clock();
   secs = (double)(t_end - t_start) / CLOCKS_PER_SEC;
   printf("Time used to process the names list and calculate the total score names: %.16g miliseconds", secs * 1000.0);
   printf("\n\n");
   /////////////////////////////////////////////////////
   
   system("pause");
   return 0;
   
   }

/*+-------------------------------------------------------------------+*/
/*| FINAL                                                             |*/
/*+-------------------------------------------------------------------


En línea

AlbertoBSD
Programador y
Moderador Global
***
Desconectado Desconectado

Mensajes: 3.696


🏴 Libertad!!!!!


Ver Perfil WWW
Re: Poner separador de miles a la hora de mostrar resultado en pantalla
« Respuesta #1 en: 11 Agosto 2016, 14:53 pm »

Compañero, da un poco de flojera leer un codigo tan largo y menos si mo esta con la etiqueta GeSHi para codigo en C

Ejemplo:

Código
  1. int var = 1;


Ve que se ve mejor.

Basicamente lo que pide se puede separar de 2 formas.

  • Procesar el dato como numero y atravez de divisiones y variables temporales ir separando en bloques de centenas y agregarles el valor adecuado
  • Convertir el Numero a cadena y procesar cada 3 caracteres y agregarles el valor adecuado

Ambas salidas deberian de devolver un string o (char*) listo para que se imprima en pantalla.

Saludos


En línea

+ 1 Oculto(s)

Desconectado Desconectado

Mensajes: 298


un defecto se puede convertir en una virtud


Ver Perfil WWW
Re: Poner separador de miles a la hora de mostrar resultado en pantalla
« Respuesta #2 en: 11 Agosto 2016, 17:26 pm »

ese codigo no parece tuyo, en fin solo deber ir dividiendo y actualizar
En línea

Yoel Alejandro

Desconectado Desconectado

Mensajes: 254



Ver Perfil WWW
Re: Poner separador de miles a la hora de mostrar resultado en pantalla
« Respuesta #3 en: 12 Agosto 2016, 16:58 pm »

Aquí un pequeño código que te da una idea de cómo podrías imprimir el número separado por miles. El trabajo lo realiza la función imprimirNumero(), luego deberás adaptarlo a tu programa específico, de la manera como esperas que trabaje.

En cuánto al programa que presentas como ejemplo, coincido con los otros foristas en que es muy extenso y parece que fue diseñado para una tarea mucho más ambiciosa que la que tú pretendes. Por lo tanto no es un buen punto de partida si sólo deseas llevar a cabo una tarea sencilla como ésta.

Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void imprimirNumero( int x );
  6.  
  7. int main()
  8. {
  9.    imprimirNumero( 2341528 );
  10.    printf( "\n" );
  11.    return 0;
  12. }
  13.  
  14. void imprimirNumero( int x )
  15. {
  16.    int BASE;
  17.    int count;
  18.  
  19.    /* determina la mayor potencia de 1000 que es menor o igual al numero */
  20.    BASE = 1;
  21.    while ( 1000 * BASE <= x ) BASE *= 1000;
  22.  
  23.    /* divide sucesivamente entre 1000 para imprimir el numero separado
  24.      * por miles */
  25.    while ( BASE > 1 ) {
  26.        printf( "%d.", x / BASE );
  27.        x = x % BASE;
  28.        BASE = BASE / 1000;
  29.    }
  30.    printf( "%d", x );
  31. }
En línea

Saludos, Yoel.
P.D..-   Para mayores dudas, puedes enviarme un mensaje personal (M.P.)
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
mostrar resultado de tabla en textbox
Programación Visual Basic
oscardiaz 4 8,088 Último mensaje 18 Septiembre 2009, 04:28 am
por oscardiaz
Mostrar resultado de un web service JSON
PHP
lucheano 9 5,574 Último mensaje 28 Septiembre 2015, 23:56 pm
por 0roch1
[AYUDA] Dos dudas para mostrar por pantalla « 1 2 »
Programación C/C++
Kougami 13 5,107 Último mensaje 10 Enero 2017, 22:56 pm
por Kougami
Como poner otra grafica a la hora de duplicar pantalla, pc a tv LG por hdmi?
Dudas Generales
Maycole 6 3,063 Último mensaje 23 Enero 2020, 10:38 am
por Maycole
Como se puede poner la hora arriba a la derecha de la pantalla?
Software
BlackMorror5 5 2,808 Último mensaje 4 Abril 2022, 20:32 pm
por .xAk.
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines