You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
16 Hrs
46 Min
21 Seg

Cómo leer datos de un usuario en C#

13/26
Resources

How to read user data in an interactive program?

Incorporating user interaction is fundamental to creating dynamic and efficient programs. In this lesson, we will explore how you can collect data directly from the console, thus improving the interactivity of your applications. We'll start by using the Console.ReadLine method in C# to allow for user input. This method will read a line from the console and will be used to assign values entered by the users to variables that we will be able to use later in our program.

How is Console.ReadLine used?

The main purpose of Console.ReadLine is to capture user input via the console. This method requires no parameters and returns a string representing the user input.

string input = Console.ReadLine();

Be sure to handle data conversions correctly, especially if you plan to use the input as a type other than the captured string.

How to convert console data to numeric types?

User input often needs conversions, especially if you are handling numbers. Herein lies the importance of understanding how to convert data types in C#:

  • To convert a string to a float number, you use float.Parse.
string input = Console.ReadLine();float number = float.Parse(input);

This code snippet takes a string entered by the user, converts it to a float and stores it in a variable.

How to improve the interaction with messages?

Be sure to guide the user through the data entry process with clear messages. You can use Console.WriteLine to print instructions or clarifications to the console. Here is an example:

Console.WriteLine("Please enter side A of the rectangle. You can use decimals:");string input = Console.ReadLine();float sideA = float.Parse(input);

This code not only prompts for input, but also provides the user with clear guidance on how to proceed.

What to do about common console errors?

When working with user input, it is crucial to handle possible syntax or formatting errors. Visual Studio provides automatic alerts in case of incorrect syntax such as omitting a semicolon. Always check for errors displayed at the bottom of the editor and correct them to ensure faster and more efficient development.

How does the locale affect data entry?

Note that number notation, such as the use of periods or commas as decimal separators, may vary depending on the locale of your computer. For example, in some Spanish-speaking countries, the use of commas is common while in others the dot is used. Therefore, adapt your program according to the user's cultural context to ensure an intuitive and error-free user experience:

Console.WriteLine("Enter side B of the rectangle using commas for decimals:");string input = Console.ReadLine();float sideB = float.Parse(input);

This practice improves the user experience and ensures that results are accurate regardless of locale.

By allowing user input and handling it properly, you are enriching the functionality and interaction of your programs. Keep practicing and feel free to experiment with different data types and settings!

Contributions 37

Questions 7

Sort by:

Want to see more contributions, questions and answers from the community?

Durante la clase vimos dos tipos de conversión, pero 🤔, ¿Cuál es la diferencia entre ambas?
‏‏‎‏‏‏‏‎‎
🥊 Convert VS. Parse 🥊

  • Ambas se pueden usar para convertir datos de un tipo a otro.
  • Convert pude manejar valores NULL retornando un 0.
  • Parse no puede manejar valores NULL y muestra un error (ArgumentNullException).
    ‎‍‍‍‍‍‎ ‏‏‎‎ ‏‏‎‎ ‏‏‎‏‏‎‎ ‏‎‎

✅ Ejemplo:
‎‍‍‍‍‍‎ ‏‏‎‎ ‏‏‎‎ ‏‏‎‏‏‎‎ ‏‏‎‎

En la variable number2 convertiremos un valor NULL en FLOAT, como sabemos nos retornara 0, por ende, el resultado de la operación es igual a 0.
😉 Puedes comprobar lo que retorna Convert imprimiéndolo por pantalla.

float number1 = 10.555f;
float number2 = Convert.ToSingle(null);
float result = number1 * number2;

Console.WriteLine($"El resultado es igual a {result}"); 

Dato: Para usar Convert para un tipo de dato FLOAT puede realizarse atreves del método .ToSingle()
‎‍‍‍‍‍‎ ‏‏‎‎ ‏‏‎‎ ‏‏‎‏‏‎‎ ‏‏‎‎

Trataremos de realizar la misma conversión, pero ahora usando Parse. Cuando ejecutemos nos mostrara un error 🥲.

‏‏‎‏‏‎‏‏‎‎‏‏

Si entendí bien al buscar la diferencia entre Convert y Parse es lo siguiente: Ambos realizan la misma función. Convert.ToInt32() llama a int.Parse() internamente. Convert.ToInt32() retorna 0 cuando el argumento es nulo, en cambio int.Parse() arroja error de valor nulo.

Que clase tan rara XD

que pasa con la edicion de este curso 😦

Console.WriteLine("Please enter the side A of the rectangle, you can use decimals");
float sideA= float.Parse(Console.ReadLine());
Console.WriteLine("Please enter the side B of the rectangle, you can use decimals");
float sideB = float.Parse(Console.ReadLine());

//rectangle area


float area = sideA * sideB;

Console.WriteLine("The rectangle area is: " + area);
Hola! el siguiente aporte es para intentar aclarar un poco la clase ya que se corta, inicia de nuevo la explicación pero con otro método de conversión. Al implementar el Convert.ToDecimal seguía apareciendo el error de conversión implícita ya que float y decimal son tipos de datos diferentes, Decimal tiene una precisión mucho más grande. Adjunto documentación para notar todas sus diferencias. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types Es por esto que después el profesor implementa el float.Parse(); Si me equivoco espero alguien me brinde retroalimentación.

En Nicargua el separador decimal es .

Asi quedo mi mini calculadora de area de rectangulos:

Adjunto el codigo, aunque la logica es la misma que la del profe:

	    float sideA = 0;
            float sideB = 0;

            Console.WriteLine("     RENCTANGLE AREA CALCULATOR\n\n");
            Console.WriteLine("              Lenght     ");
            Console.WriteLine("        *****************");
            Console.WriteLine("        *               *");
            Console.WriteLine("   Width*               *");
            Console.WriteLine("        *               *");
            Console.WriteLine("        *****************\n\n");

            Console.WriteLine("Insert the lenght of the rectangle:");
            sideA = float.Parse(Console.ReadLine());

            Console.WriteLine("Insert the width of the rectangle:");
            sideB = float.Parse(Console.ReadLine());

            //Renctangle area formula is a*b

            float area = sideA * sideB;
            Console.WriteLine("The rectangle area is: " + area);

Logré hacer mi propia calculadora de áreas de 4 figuras distintas (2 de ellas son cuadriláteros). La hice a prueba de errores de sintaxis, por eso tiene muchos if elses. Tal vez alguien me podría decir si es que se puede compactar aún más el código, sin tener que quitar esos textos anti errores.

Console.WriteLine("This program calculates the area of the following figures: triangle, rectangle, trapeze, circle. Type the figure from which you want to calculate its area.");
string figure = Console.ReadLine();
if (figure == "triangle")
{
    Console.WriteLine("Please type the height:");
    decimal height = Convert.ToDecimal(Console.ReadLine());
    Console.WriteLine("Now type the base's length:");
    decimal figureBase = Convert.ToDecimal(Console.ReadLine());
    decimal result = height * figureBase / 2;
    if (height != 0 && figureBase != 0)
    {
        Console.WriteLine("The area of a triangle with a base of " + figureBase + " and a height of " + height + " is " + result);
    }else
    {
        if (height == 0 && figureBase != 0)
        {
            Console.WriteLine("A triangle cannot have a height that measures 0");
        }else
        {
            if (height != 0 && figureBase == 0)
            {
                Console.WriteLine("A triangle cannot have a side that measures 0");
            }
            else
            {
                if (height == 0 && figureBase == 0)
                {
                    Console.WriteLine("A triangle cannot have a height nor a side that measures 0");
                }
            }
        }
    }
    
}
else
{
    if (figure == "rectangle")
    {
        Console.WriteLine("Please type the height:");
        decimal height = Convert.ToDecimal(Console.ReadLine());
        Console.WriteLine("Now type the base's length:");
        decimal figureBase = Convert.ToDecimal(Console.ReadLine());
        decimal result = height * figureBase;
        if (height != 0 && figureBase != 0)
        {
            if (height == figureBase)
            {
                Console.WriteLine("The area of a square with a base of " + figureBase + " and a height of " + height + " is " + result);
            }
            else
            {
                Console.WriteLine("The area of a rectangle with a base of " + figureBase + " and a height of " + height + " is " + result);
            }
        }
        else
        {
            Console.WriteLine("A rectangle cannot have a side that measures 0");
        }
        
    }
    else
    {
        if (figure == "trapeze")
        {
            Console.WriteLine("Please type the height:");
            decimal height = Convert.ToDecimal(Console.ReadLine());
            Console.WriteLine("Now type the smallest base's length:");
            decimal trapezeBase1 = Convert.ToDecimal(Console.ReadLine());
            Console.WriteLine("And now type the largest base's length:");
            decimal trapezeBase2 = Convert.ToDecimal(Console.ReadLine());
            decimal result = height * (trapezeBase1 + trapezeBase2) / 2;
            if (height != 0 && trapezeBase1 != 0 && trapezeBase2 != 0)
            {
                if (trapezeBase1 > trapezeBase2)
                {
                    Console.WriteLine("You were supposed to write the smallest base's length when it was asked to type the smallest base's length, but you typed the largest one's. Anyways, the answer is " + result);
                }
                else
                {
                    if (trapezeBase1 == trapezeBase2)
                    {
                        if (trapezeBase1 == height)
                        {
                            Console.WriteLine("This is a square, not a trapeze. Anyways, the answer is " + result);
                        }
                        else
                        {
                            Console.WriteLine("This is a rectangle, not a trapeze. Anyways, the answer is " + result);
                        }
                    }
                    else
                    {
                        Console.WriteLine("The area of a trapeze with a height of " + height + ", a smaller base of " + trapezeBase1 + " and a larger base of " + trapezeBase2 + " is " + result);
                    }
                }
            }
            else
            {
                if (height == 0 && trapezeBase1 != 0 && trapezeBase2 != 0)
                {
                    Console.WriteLine("A trapeze cannot have a height of 0");
                }
                else
                {
                    if (height != 0)
                    {
                        if (trapezeBase1 == 0 || trapezeBase2 == 0)
                        {
                            Console.WriteLine("A trapeze cannot have a base of 0");
                        }
                    }
                    else
                    {
                        Console.WriteLine("A trapeze cannot have a height nor a base of 0");
                    }
                }
            }
        }
        else
        {
            if (figure == "circle")
            {
                Console.WriteLine("Please type the radius:");
                decimal radius = Convert.ToDecimal(Console.ReadLine());
                decimal Pi = 3.14159265358979323846M;
                decimal result = radius * radius * Pi;
                if (radius != 0)
                {
                    Console.WriteLine("The area of a circle with a radius of " + radius + ", considering the first 20 decimal digits of Pi, is " + result);
                }
                else
                {
                    Console.WriteLine("A circle cannot have a radius of 0");
                }
            }
        }
    }
}

En México utilizamos en punto(.) para realizar la separación de los números enteros y números decimales.

static void Main(string[] args)
        {
            //rectangle area calc.

            //rectangle values
            Console.Write("Please enter the side A of the rectangle, you can use decimals: ");
            double sideA = double.Parse(Console.ReadLine());

            Console.Write("Please enter the side B of the rectangle, you can use decimals: ");
            double sideB = double.Parse(Console.ReadLine());

            //rectangle area formula is a*b
            double area = sideA * sideB;

            Console.WriteLine("The rectangle area is: " + area);
        }

Les comparto mi codigo:

using System;
namespace _13_LeerDatosDeUnUsuario
{
    class Program
    {
        static void Main()
        {
            /* *** Leer datos *** */
            Console.WriteLine("*** Area de un rectangulo ***");
            Console.WriteLine("★ Ingresa el lado A: ");
            float sideA = float.Parse(Console.ReadLine()!);
            Console.WriteLine("★ Ingresa el lado B: ");
            float sideB = float.Parse(Console.ReadLine()!);

            Console.WriteLine($"El area es: { sideA * sideB }");

        }
    }
}

Y el resultado en consola:

*** Area de un rectangulo ***
 Ingresa el lado A: 
10
 Ingresa el lado B: 
20
El area es: 200

Repasando ando

Console.WriteLine("Write the magnintud of the side A(You can use decimals, the separator is ,):" );
float sideA1 = float.Parse(Console.ReadLine());
Console.WriteLine("Write the magnintud of the side B(You can use decimals, the separator is ,):");
float sideB1 = float.Parse(Console.ReadLine());

float area1 = sideA1 * sideB1;
Console.WriteLine("The area of the rectangule is :" + area1 + "\n Side A: " + sideA1 + "\n Side B: " + sideB1);

Mi teoria es que estos errores son por presion de cambiar de visual code a visual normal, se ve que uno fue grabado con code y otro con visual, tambien he visto cambios de visual 2019 a 2022 en varios cursos.

Este video está mal editado, se repite el inicio casi a la mitad del video y la repetiión de las correcciones de los errores.

Esta clase está mal planeada o simplemente mal editada. 👆

No entiendo porque en los comentarios hablan de la función convert de la clase… solo se mostró el Parse.
Raro, vi de nuevo la clase para ver si me lo había perdido…

yo hice una igual pero también mi código ve si el numero que ingresa es divisible por 3.
espero que alguien le sirva.

<code> 
console.WriteLine("plesae enter a number type float: ");
float sideA = float.Parse(Console.ReadLine());//no se puede mandaru mensaje
int sideB = 3;

float result = (sideB  %  3);//false
if (result == 0)
{
    Console.WriteLine("es divisible por 3:  "+ sideA);
    
}
else
{
    Console.WriteLine("no es divisible por 3: "+ sideA); 
}


float area = sideA * sideB;

Console.WriteLine("the rectangule area is: "+ area);

Aca en Colombia se separa los decimales con ,

Investigando un poco me encontré con que “la coma se emplea en la Argentina, Chile, Colombia, el Ecuador, España, el Paraguay, el Perú y el Uruguay; - el punto se emplea en México, Guatemala, Honduras, Nicaragua, Panamá, Puerto Rico, la República Dominicana y Venezuela; - ambos, la coma y el punto, se usan en Bolivia, Costa Rica, Cuba y el Salvador”.

Console.WriteLine("Ingrese el lado A de nuestro rectangulo: ");
float value1 = float.Parse(Console.ReadLine());
Console.WriteLine("Ingrese el lado B de nuestro rectangulo: ");
float value2 = float.Parse(Console.ReadLine());

float area = value1 * value2;
Console.WriteLine("El area del rectangulo es: " + area);



//internal class Program
{
static void Main(string[] args)
{
// Read the user name and data from the console
// Variables to store the user name and data
string userFirstName, userLastName, userEmail, userPhone = “”;
// Read the user name and data from the console
Console.WriteLine("Enter your first name: ");
userFirstName = Console.ReadLine();
Console.WriteLine("Enter your last name: ");
userLastName = Console.ReadLine();
Console.WriteLine("Enter your email: ");
userEmail = Console.ReadLine();
Console.WriteLine(“Enter your phone: “);
userPhone = Console.ReadLine();
// Print the user name and data to the console
Console.WriteLine(”");
Console.WriteLine("Data user is: “);
Console.WriteLine(”
”);
Console.WriteLine("First name: " + userFirstName);
Console.WriteLine("Last name: " + userLastName);
Console.WriteLine(“Email: " + userEmail);
Console.WriteLine(“Phone: " + userPhone);
Console.WriteLine(”============================================================================”);
Console.ReadLine();
}
}

en ese caso aplicar antes de la conversión str.Replace(’ .’, ‘,’) siendo str el string o Console.ReadLine para que tome bien el decimal indistinto si lo escriben con . o ,

Para comentar en bloque puedes usar:

/* al inicio del bloque.
*/ al final del bloque.

Como este ejercicio usa otro proyecto que ya habíamos realizado, es muy probable que quieras comentar las líneas del ejercicio anterior.

Yo no se porque, pero a mi si me funciona el “.” en lugar de la “,”.

Creo que se debería aclarar que el tema de los separadores no depende tanto del estándar que se use en el país (evidentemente cuando establecemos una configuración regional hay un comportamiento por defecto), sino de la configuración que el propio usuario puede definir en su equipo y/o programas .

Hola! hice este ejercicio, espero les sirva mi aporta 😃

Console.WriteLine("Enter your first name:");
string fname = Console.ReadLine();

Console.WriteLine("Enter your last name:");
string lname = Console.ReadLine();

//Los datos que salen de los inputs son si o si strings, se usa el .Parse para convertirlos
Console.WriteLine("Enter your DNI:");
float dni = float.Parse(Console.ReadLine());

Console.WriteLine("Enter the quantity of apples you want to buy: 0:");
int apples = int.Parse(Console.ReadLine());

Console.WriteLine("First name: " + fname);
Console.WriteLine("Last name: " + lname);
Console.WriteLine("DNI: " + dni);
Console.WriteLine("Apples: " + apples);

En el minuto 4:34 se reinicia la clase, corregir por favor.

Hola #PlatziTeam esta clase amerita algunos ajustes por favor… después de 8 minutos la información está duplicada…}
Muchas gracias por el apoyo.!

No se como no les da vergüenza, en fin me sacaron un risa de lo mal que esta hecho.

Este video si que les salio muy mal editado

esta clase esta mal editada

Si tiene unos errores de edición son notables

Esta clase de verdad fue muy extraña.
Yo escucho la clase mientras escribo y practico el código, Así que por momentos creí que el video se iba a puntos anteriores, pero no era así.
No sé si sea mala edición o mala planeación, pero a pesar de que los conocimientos expuestos se entienden, es difícil entender todo.

ESTA CLASE ESTA MAL EDITADA

Aunque no logre terminar de entender las diferencias, en esta
pregunta se explica la diferencia entre hacer el casteo con Convert.ToString() y (string) variableNoString