Do I need to use "Convert.Toint32()" for text?

Asked

Viewed 527 times

1

I think it’s something with the Convert.ToInt32(), because I didn’t understand its function inside the language.

Observation 1:
The place where I learn is American and I don’t know much English.

Observation 2:
This is the code:

using.system;
using.system.Collections.Generic;
using.system.Ling;
using.system.Text;
using.Threading.Tasks;
    
namespace T1
{ 
    class Program
    {
        static void Main(string[] args)
        {
            string x = convert.ToInt32(Console.ReadLine())
            console.WriteLine("{0}", x);
        }
    }
}

3 answers

5


My first suggestion is to look for some source that is easier for you. I advise to try to understand all aspects of programming before, or at least in the language. Learning language is easy, learning to program is much harder and doesn’t usually work well when one tries to learn programming along with the language.

You want to read something from the console, that is, you want to let the user type something, right? Then you chose the correct method. The ReadLine() order to read a line on the console. Click on it and see the documentation. It is always important to read all documentation carefully before using anything. It says that the return from method is a value of type string.

What do you want to do? Print this? Ok, no conversion required after all strings are the only things you can actually print in a way that the human being can understand. Even when printing a number it needs to be converted to string to print. And generally this conversion occurs automatically by the printing method.

Let’s organize the code and fix the syntax errors. Organizing helps understand the code, and the sooner you realize this importance, the faster it will evolve. And writing everything right is fundamental for the code to compile, work and be right. Pointing out that it works is different from being right. What you should always look for is to be right, more than work.

using System;

namespace T1 { 
    public class Program {
        public static void Main(string[] args) {
            string x = Console.ReadLine();
            Console.WriteLine("{0}", x);
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • I took out the unnecessary importers for this code,
  • I have correctly identified,
  • I capitalized what needs to be (this counts, Console is different console,
  • placed ; where he needed,
  • fixed the using I had a point where I shouldn’t.

In this example we can simplify even more. Variables are memory storage locations with a name to facilitate the programmer’s understanding. Do you need to store some value in this example? No, you need a value but not store it. I will then remove it.

In general in simple codes do not need to create a namespace. Removing it simplifies a little more. Namespaces are used to organize very large code, which is not the case.

C# allows interpolation of strings, that is, you can put code inside the quotes and it will be considered part of the code and not part of the text. This can be a simplification.

You can import a static class if you want, then the code gets shorter. In this case the gain is not great, but you can get used to it:

using static System.Console;

public class Program {
    public static void Main(string[] args) => WriteLine($"{ReadLine()}");
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

When you need to calculate something that is in text format, you need to convert it to numbers. The method Convert.ToInt32() can be used when you are sure that the conversion will work. It is not the case of a given entered by keyboard. The user can type something that cannot be converted to number. In this case the best thing to do is to try the conversion and only if it works will you use the value obtained. We use the TryParse() for this (see also).

I’ll use comments for educational purposes, but do not abuse them under normal conditions.

I’ll use the var to introduce a new concept for you. It "discovers" the type of the variable itself, if you have something that allows the compiler to do this. Just don’t abuse it.

I don’t know if you’ve learned to use the if, he is one of the most important things in programming and has a lot of "experienced" programmer who still doesn’t know how to use it properly, despite being easy. It makes decisions whether a block of commands will be executed or not. It needs a boolean value, that is, it needs to be true or false. If you don’t know this, ask specific questions.

The method TryParse() returns just one boolean indicating whether the conversion operation was successful or not. If it is, it stores the converted value in the argument outgoing (out) method. As there are two conversion, we get the two results and applications an operator of and, that is, the end result will only be true if both are true (is another language, but it works the same).

Storage is now required, so we create variables.

using static System.Console;

public class Program {
    public static void Main(string[] args) {
        var texto1 = ReadLine(); //pede o texto e armazena em variável
        int numero1; //declara a variável que receberá o número1
        var texto2 = ReadLine(); //pede o texto e armazena em variável
        int numero2; //declara a variável que receebrá o número2
        if (int.TryParse(texto1, out numero1) && int.TryParse(texto2, out numero2)) WriteLine($"{texto1} + {texto2} = {numero1 + numero2}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

0

Friend, first of all: C# is case sensitive. That is, it differentiates capital letters from minuscules. I don’t know if it was time to pass your code here but you’re calling Convert instead of Convert and console instead of Console.

Second: the method of Convert.ToInt32(string value); converts a value passed as parameter to a 32-bit integer. If the value passed is not a valid integer, it will throw an exception (Formatexception).

Third (which I believe is your problem): as I said, the return of this method is a whole. Note that your variable x is of the type string. One string cannot receive a whole directly. Or you change the type of variable x to int, or you use a .ToString() to effect the conversion.

getting:

int x = Convert.ToInt32(Console.ReadLine());

or

string x = Convert.ToInt32(Console.ReadLine()).ToString();

It is well acceptable and even elegant to declare your variable with var. This way you instruct the compiler to deduce the type that will be received by the variable.

var x = Convert.ToInt32(Console.ReadLine());

Remembering that, as there is no validation of what the user inserts in the console, an Exception can be launched if it enters an invalid value (a letter for example).

0

First of all I should specify where the error occurs, so I can’t see what is wrong with the code, but it is noteworthy that what comes in the string has to be a number (If you are wrong correct) because if it is not will give error. When you are not sure what comes in the string (whether a number comes or not) see what it is and use the int.Tryparse

Browser other questions tagged

You are not signed in. Login or sign up in order to post.