Why output is printed in asci code instead of integer ?dart

173

Solution 1

Get the value as String using stdin.readLineSync() then parse it to int like below:

import 'dart:io';

void main() {
  int n = 0;
  print("input: ");

  do {
    n = int.parse(stdin.readLineSync());
  } while (n>1000 || n<0);

  if (n % 4 == 0) {
    print("output: ");
    print(n);
    n++;
  } else {
    print("output: ");
    n--;
    print(n);
  }
}

Solution 2

Paste your code so it can be easier to help you. I could have given you a fixed source code if you would have provided.

Instead, I'll try to explain: Your stdin will be provided as a string, you read it as bytes so 5 will be come 35 as hex. When you print it, my guess is that it will automatically be converted to a decimal value (53, and the output shows 52 because 53 % 4 = 1 and then to decrease with n-- before printing it so it become 52). Those numbers like you said of the ASCII Table. In order to fix it, make sure you have the string representation of the input (stdin). Then convert the value to integer: "2".toInt()

Edit: I could have easily find the complete solution, You need to get the stdin as a string first: readLineSync and convert it to int:

n = int.parse(stdin.readLineSync());

Note: Code not tested, but it's pretty straight forward.

Share:
173
Sport CAST
Author by

Sport CAST

Updated on December 06, 2022

Comments

  • Sport CAST
    Sport CAST over 1 year

    I don't know why output is printed in ascii code instead of integer value ,what wrong with my code ?

    import 'dart:io';
    
    void main() {
      int n = 0;
      print("input: ");
    
      do {
        n = stdin.readByteSync();
      } while (n>1000 || n<0);
    
      if (n % 4 == 0) {
        print("output: ");
        print(n);
        n++;
      } else {
        print("output: ");
        n--;
        print(n);
      }
    }
    

    output

    • Blasanka
      Blasanka almost 6 years
      Can you instead of a screenshot, add your code?
  • Blasanka
    Blasanka almost 6 years
    String doesn't have a toInt() instead use int.parse()
  • Sport CAST
    Sport CAST almost 6 years
    the output is showed correctly after i used int.parse .Thank you for the explanation