How to read multiple values in a single line on Dart?

Asked

Viewed 31 times

0

How do I read more than one value in a single line? For the exercise I’m doing says the following:

the input file contains two rows of data. In each row there will be 3 values, respectively two integers and a value with 2 decimal places. For example:

12 1 5.30

16 2 5.10

I tried to do the exercise using the method: stdin.readLineSync(), but he always jumps to the next line.

  int codigoPeca1 = int.tryParse(stdin.readLineSync());
  int numeroPeca1 = int.tryParse(stdin.readLineSync());
  double valorUnitarioPeca1 = double.tryParse(stdin.readLineSync());

  int codigoPeca2 = int.tryParse(stdin.readLineSync());
  int numeroPeca2 = int.tryParse(stdin.readLineSync());
  double valorUnitarioPeca2 = double.tryParse(stdin.readLineSync());

I’ve already searched and found nothing related in Dart.

1 answer

0


You can use the function split() that breaks the String according to the tab you inform and turns into a List.

So you only need to recur only once the value and then treat it to be used in the other variables.

Here is an example, for your case where you recover the value of the values input:

void main() {
  // Aqui seria o stdin.readLineSync()
  final dadosEntrada = "12 1 5.30";
  
  // Quebra os valores em itens de um array a cada espaço encontrado
  // Retorno: [12, 1, 5.30]
  final List<String> valoresSeparados = dadosEntrada.split(" ");
  
  // Pega o item respectivo do array e transforma em int ou double, retornando 0 (zero) caso não consiga converter corretamente
  int codigoPeca1 = int.tryParse(valoresSeparados[0]) ?? 0;
  int numeroPeca1 = int.tryParse(valoresSeparados[1]) ?? 0;
  double valorUnitarioPeca1 = double.tryParse(valoresSeparados[2]) ?? 0.0;
  
  print("codigoPeca1: $codigoPeca1 || numeroPeca1: $numeroPeca1 || valorUnitarioPeca1: $valorUnitarioPeca1");
}

Note: You can run this code on Dartpad to see how it works.

  • 1

    Thank you so much for helping Matheus! I studied the code and managed to solve my problem.

Browser other questions tagged

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