How to read keyboard numbers in C #?

0

I know that getchar() gets keyboard characters by stdin , however I want to know how to enter numbers in a variable.

If I use getchar() and I type a 2 , for example, the variable becomes 50 , and obviously it's not what I want.

    
asked by anonymous 30.06.2016 / 00:23

3 answers

5

Well, you did not specify the language, so come on:

C

To read a number, I will assume it is an int, in C the following code is used:

int meuNumero; scanf("%d", &meuNumero);

C ++

To read a number in C ++ we use the stream cin with the >> operator:

int meuNumero; cin >> meuNumero;

C #

In C # we have to call the Console.ReadLine method to read the input and Convert.ToInt32 or Int32.Parse to transform to a number:

int meuNumero = Convert.ToInt32(Console.ReadLine())
    
30.06.2016 / 00:41
3

If it's C # you can use Console.ReadLine() but do not forget that ReadLine() returns a String, so you need to convert. You can use Convert.ToInt32(Console.ReadLine()); .

So it stays: int input = Convert.ToInt32(Console.ReadLine()); .

If you enter a String other than int, you will probably receive an exception.

If you are using C, with the stdio.h library, you will be able to catch an int using the famous scanf() .

Then stay:

int input;
scanf("%d", &input);

Finally, if you have C ++, you can always use the sdt namespace.

Then stay:

int input;
std::cin >> input;

I hope I have helped.

    
30.06.2016 / 00:40
1

In language C, use getch() to capture the first character typed, eg

char op;
op=getch(); //Lê a primeira tecla que for digitado no teclado, e grava na variável
printf("Caractere digitado: %c", op); //Printa na tela o caractere digitado

If you want to record more than one character in a variable it uses scanf() as already exemplified in other responses.

If you want to get only numbers and make calculations with them use scanf() using variables of type int for integers and float for non integers, for example:

//Fazendo cálculos com números inteiros
int a, b, result_int;
printf("Digite o primeiro valor: \n");
scanf("%d", &a);
printf("Digite o segundo valor: \n");
scanf("%d", &b);

result_int = a + b;
printf("a + b = %d\n", result_int); //Printa na tela o resultado da soma

//Fazendo cálculos com números não inteiros
float c, d, result_float;
printf("Digite o primeiro valor: \n");
scanf("%f", &c);
printf("Digite o segundo valor: \n");
scanf("%f", &d);

result_float = c + d;
printf("c + d = %f\n", result_float); //Printa na tela o resultado da soma
printf("c + d = %.2f\n", result_float); //Printa na tela o resultado da soma, limitando as casas depois da virgula para melhor visual

Compile the code for you to understand better.

    
02.07.2016 / 05:39