Text Formatting


Text Formatting

Text formatting consists of combining numeric values, text and other information to create some output text. In the program below Sys::TextAssistant::Format will produce some formatted text by combining the text and the numeric value. Specifically, Sys::TextAssistant::Format will replace the %d with the value stored in count.
El formateo de texto consiste en combinar valores numéricos, texto u otra información para crear un texto de salida. En el programa de abajo Sys::TextAssistant::Format create un texto con formato al combinar el texto y el valor numérico. Específicamente, Sys::TextAssistant::Format reemplazará el %d con el valor almacenado en count.

Format

Tip
It is possible to format a wchar_t variable using the command_snwprintf_s as shown below. One of the main advantages of using wstring is that the programmer does not have to worry about the capacity of the text variable.
Es posible formatear una variable del tipo wchar_t usando el comando _snwprintf_s como se muestra debajo. Una de las principales ventajas de usar wstring es que el programador no se tiene que preocupar por la capacidad de la variable de texto.

FormatWchar

wstring vs wchar_t*

Text functions may take a wstring variable or a wchar_t* variable, both of them are used to transfer text from one place of the program to another part. The only case that requires conversion occurs when we have a wstring variable, and the function takes a wchar_t* variable as it illustrated in the figure below.
Las funciones de texto pueden tomar una variable del tipo wstring o una variable wchar_t*, ambas son usadas para mover texto de una parte del programa a otra. El único caso que requiere conversión ocurre cuando tenemos una variable wstring, y la función toma una variable wchar_t* como se ilustra en la figura de abajo.

WchartVsWstring

Problem 1
Create a program called Formatting to display a double value using several formatting options.
Cree un programa llamado Formatting para mostrar un valor double usando varias opciones de formateo.

Formatting.cpp
void Formatting::Window_Open(Win::Event& e)
{
     const double weight = 123.00000;
     wstring text;
     Sys::TextAssistant::Format(text, L"%f", weight);
     this->MessageBox(text, L"Format", MB_OK);
     //
     Sys::TextAssistant::Format(text, L"%.2f", weight);
     this->MessageBox(text, L"Format", MB_OK);
     //
     Sys::TextAssistant::Format(text, L"%g", weight);
     this->MessageBox(text, L"Format", MB_OK);
}


Tip
The table below summarizes the basic text formatting options. Note that all formatting options begin with %. Each time an % appears in the formatting string, the computer will replace it with the respective value provided.
La tabla de abajo resume las opciones básicas para formatear texto. Note que todas las opciones de formato comienzan con %. Cada vez que un % aparece en la cadena de formato, la computadora la reemplazara con el valor respectivo proporcionado.

Tip
The percent sign is, therefore a reserved character and if you want to display the percent sign, you must escape it by writing two percent signs together. Other special characters are: backslash and quotes.
El signo de porcentaje es, por lo tanto un caracter reservado y si usted quiere mostrar el signo de porcentaje, usted debe escaparlo escribiendo dos signos de porcentaje juntos. Otro caracteres especiales son: la diagonal invertida y las comillas.

FormatOptions

Tip
Most text functions that were created before wstring can be used by converting the wstring variable to wchar_t. A wstring variable can easily be converted to a wchar_t type as shown in the example below.
L a mayoría de las funciones que fueron creadas antes de wstring pueden ser usadas convirtiendo la variable wstring a wchar_t. Una variable del tipo wstring puede ser facilmente convertida a una del tipo wchar_t como se muestra en el ejemplo de abajo.

Program.cpp
void Program::Window_Open(Win::Event& e)
{
     wstring text;
     wstring name = L"Steve";
     Sys::TextAssistant::Format(text, L"%s is young", name.c_str()); //.c_str() converts the wstring variable to wchar_t
     this->MessageBox(text, L"Format", MB_OK);
}


Problem 2
Create a program called Sensores to display the specifications of a sensor: name, weights and dimensions.
Cree un programa llamado Sensores para mostrar las especificaciones de un sensor: nombre, peso y dimensiones.

Sensores

Tip
Observe the in the previous problem: the carriage return and the new line commands, \r\n, are used to write the text in several lines.
Observe que en el problema anterior: el retorno de carro y el comando de línea nueva, \r\n, son usados para escribir texto en varias líneas.

Problem 3.
Repeat the previous problem using Java, called your project SensoresJ.
Repetir el problema previo usando Java, llame a su proyecto SensoresJ.

Sensores.java
public class Main
{
     public static void main(String[] args)
     {
          String name = "Termometro";
          double weight = 49.0; //gr
          int width = 4; //cm
          int height = 10; //cm
          int depth = 5; //cm
          String text;
          text = "Name: " + nombre + "\r\nWeight: " + weight + " gr\r\nSize: " + width + " cm x " + height + " cm x " + depth +" cm";
          javax.swing.JOptionPane.showMessageDialog(null, texto);
     }
}


Problem 4.
Repeat the previous problem using C#, called your project SensoresS.
Repetir el problema previo usando C#, llame a su proyecto SensoresS.

SensoresSRun

Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SensoresS
{
     static class Program
     {
          /// <summary>
          /// The main entry point for the application.
          /// </summary>
          [STAThread]
          static void Main()
          {
               Application.EnableVisualStyles();
               Application.SetCompatibleTextRenderingDefault(false);
               //Application.Run(new Form1());
               String name = "Termometro";
               double weight = 49.0; //gr
               int width = 4; //cm
               int height = 10; //cm
               int depth = 5; //cm
               string texto = "Name: " + name + "\r\nWeight: " + weight.ToString("0.000") + " gr\r\nSize: " + width + " cm x " + height + " cm x " + depth + " cm";
               MessageBox.Show(texto, "Resultado", MessageBoxButtons.OK);
          }
     }
}


Table of Variables

Some programmers use a table of variables to debug a program manually. The program below illustrates the proper use of this table. Note that there is one column in the table for each variable in the program.
Algunos programadores usan una tabla de variables para depurar un programa manualmente. El programa de abajo lustra el uso adecuado de esta tabla. Note que hay una columna en la tabla por cada variable en el programa.

VariableTable

Problem 5.
Compute the table of variables and draw the output of the program. Use Microsoft Excel to build the table.
Calcule la tabla de variables y dibuje la salida producida por el programa. Utilice Microsoft Excel para construir la tabla.

Program.cpp
void Program::Window_Open(Win::Event& e)
{
     int temperatura = 24;
     int peso = 60;
     wstring texto;
     peso *= 2;

     Sys::TextAssistant::Format(texto, L"%i -> %i, %i -> %i ", temperatura, 2*temperatura, peso, peso+7);
     this->MessageBox(texto, L"Resultado", MB_OK);
}

tvTempPesoText

Problem 6.
Indicate whether it is true or false: In a Sys::Format command the number of: %d, %s, %g, etc., must be equal to the the number of variable provided by the end of the command.
Diga si es cierto o falso: En un comando de Sys::Format el número de: %d, %s, %g, etc., debe ser igual al número de variables proporcionadas para el final del comando.

Problem 7.
Indicate whether it is true or false: In a Sys::Format command the selected format type: %i, %d, %s, %g, etc., must be assigned using the data type of the variables provided by the end of the command. For instance, if the first format command is %d or %i, the first provided variable must be of the data type integer.
Diga si es cierto o falso: En un comando de Sys::Format el tipo de formato seleccionado: %i, %d, %s, %g, etc., debe coincidir con los tipos de variables proporcionadas al final del comando. Por ejemplo: si el primer comando de formato es %d or %i , la primer variable proporcionada debe ser del tipo de datos entera.

Floating Point Values

The numeric values that are not integer are stored in the computer as floating point numbers. Internally, these numbers have three parts: a sign (positive or negative), a mantissa (which is bigger than one and less than two and have two fixed digits), and one exponent. Inside the computer, of course, the mantissa and the exponent are binary values. The figure below shows a floating point value and its parts.
Los valores numéricos que no son enteros son almacenados como números de punto flotante. Internamente, los números de punto flotante tienen tres partes: un signo (positivo o negativo), una mantisa (la cual es un valor mayor a uno y menor a dos y tienen un número fijo de dígitos), y un exponente. Dentro de la computadora, por supuesto, la mantisa y el exponente son valores binarios. La figura de abajo muestra un valor de punto flotante y sus partes.

FloatingPointValue

Casting

Casting allows converting a variable from one data type into another data type. For instance, a floating point value (double) can be converted to an integer value as it is shown below. Casting notifies to the compiler that the programmer takes full responsibility of the consequences of the conversion. In the example, the programmer accepts that the the decimal part (0.7 of the floating value) will be lost.
El casteamiento permite convertir una variable desde un cierto tipo de datos a otro tipo. Por ejemplo, una variable de punto flotante (double) puede convertirse a un valor entero como se muestra debajo. El casteamiento notifica al compilador que el programador toma responsabilidad completa de las consecuencias de la conversion. En el ejemplo de abajo el programador acepta perder la parte decimal (0.7) del número de punto flotante.

Program.cpp
void Program::Window_Open(Win::Event& e)
{
     int temperatura = (int)6.7; // temperature = 6
}


Problem 8.
Compute the table of variables and draw the output of the program. Use Microsoft Excel to build the table. Create a Microsoft Visual Studio project called MyPeso to test your results.
Calcule la tabla de variables y dibuje la salida producida por el programa. Utilice Microsoft Excel para construir la tabla. Cree un proyecto de Microsoft Visual Studio llamado MyPeso para probar sus resultados.

MyPeso.cpp
void MyPeso::Window_Open(Win::Event& e)
{
     int temperatura = 24;
     int peso = 60;
     wstring texto;
     peso /= (int)10.5;

     Sys::TextAssistant::Format(texto, L"(%i, %i) -> (%i, %i)", temperatura/2, 5+temperatura, peso*2, peso-1);
     this->MessageBox(texto, L"Resultado", MB_OK);
}

tvTempPesoText

Problem 9.
Compute the table of variables and draw the output of the program. Use Microsoft Excel to build the table. Create a Microsoft Visual Studio project called Calor to test your results.
Calcule la tabla de variables y dibuje la salida producida por el programa. Utilice Microsoft Excel para construir la tabla. Cree un proyecto de Microsoft Visual Studio llamado Calor para probar sus resultados.

Calor.cpp
void Calor::Window_Open(Win::Event& e)
{
     const double temperatura = 24.3;
     int peso = 60;
     wstring info;
     wstring details;
     peso = 50;
     Sys::TextAssistant::Format(info, L"The temperature is %.1f C", temperatura/3);
     Sys::TextAssistant::Format(details, L"El peso es %d Kg", peso/2);
     this->MessageBox(info, details, MB_OK);
}

tvInfoDetails

Problem 10.
Compute the table of variables and draw the output of the program. Use Microsoft Excel to build the table. Create a Microsoft Visual Studio project called Rojo to test your results.
Calcule la tabla de variables y dibuje la salida producida por el programa. Utilice Microsoft Excel para construir la tabla. Cree un proyecto de Microsoft Visual Studio llamado Rojo para probar sus resultados.

Rojo.cpp
void Rojo::Window_Open(Win::Event& e)
{
     int temperatura = 24, edad = 19;
     int peso = 60;
     wstring texto;
     edad-=10;
     Sys::TextAssistant::Format(texto, L"(%i, %d) -> (%i, %i)", temperatura/2, 5+temperatura, edad, peso-1);
     this->MessageBox(texto, L"Resultado", MB_OK);
     this->MessageBox(texto, L"Resultado", MB_OK);
}

tvTempPesoEdadTexto

Problem 11.
Compute the table of variables and draw the output of the program.
Calcule la tabla de variables y dibuje la salida producida por el programa.

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     int temperatura = 22, edad = 19;
     int peso = 57;
     wstring texto;
     edad = 20;
     peso /= 2;
     temperatura = 18 *2;
     Sys::TextAssistant::Format(texto, L"(%i, %i) -> (%i, %i)", temperatura/3, 5+temperatura, edad, peso+1);
     this->MessageBox(texto, L"Resultado", MB_OK);
     this->MessageBox(L"Hola", texto, MB_OK);
     this->MessageBox(texto, texto, MB_OK);
}

tvTempPesoEdadTexto

Problem 12.
Compute the table of variables and draw the output of the program.
Calcule la tabla de variables y dibuje la salida producida por el programa.

Program.cpp
void Programa::Window_Open(Win::Event& e)
{
     int temperatura = 22, edad = 19;
     double peso = 57/10;
     wchar_t texto[256];
     _snwprintf_s(texto, 256, _TRUNCATE, L"(%i, %g) ", temperatura, peso-1);
      this->MessageBox(texto, L"Seven", MB_OK);
      edad = 20 + 5;
      _snwprintf_s(texto, 256, _TRUNCATE, L"%d)***(%.2f", edad+2, peso*2);
     this->MessageBox(texto, L"Six", MB_OK);
}

tvTempPesoEdadTexto

Problem 13.
Create a Wintempla program called Pies to convert inches to feet as shown.
Cree un programa de Wintempla llamado Pies para convertir pulgadas a pies como se muestra.

Pies

Problem 14
Repeat the previous problem using Win32 only. Called your project Pies32.
Repetir el problema anterior usando solamente Win32. Llame a su proyecto Pies32.

Problem 15
Repeat the previous problem using Java. Called your project PiesJ.
Repetir el problema anterior usando Java. Llame a su proyecto PiesJ.

Problem 16
Repeat the previous problem using C#. Called your project PiesS.
Repetir el problema anterior usando C#. Llame a su proyecto PiesS.

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home