How do I read console input / stdin in Dart?

前端 未结 4 866
你的背包
你的背包 2021-02-03 21:58

How do I read console input from stdin in Dart?

Is there a scanf in Dart?

相关标签:
4条回答
  • 2021-02-03 22:46

    With M3 dart classes like StringInputStream are replaced with Stream, try this:

    import 'dart:io';
    import 'dart:async';
    
    void main() {
      print("Please, enter a line \n");
      Stream cmdLine = stdin
          .transform(new StringDecoder())
          .transform(new LineTransformer());
    
      StreamSubscription cmdSubscription = cmdLine.listen(
        (line) => print('Entered line: $line '),
        onDone: () => print(' finished'),
        onError: (e) => /* Error on input. */);
    
    
    }
    
    0 讨论(0)
  • 2021-02-03 22:50

    The readLineSync() method of stdin allows to capture a String from the console:

    import 'dart:io';
    
    main() {
        print('1 + 1 = ...');
        var line = stdin.readLineSync(encoding: Encoding.getByName('utf-8'));
        print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
    }
    
    0 讨论(0)
  • 2021-02-03 22:57
    import 'dart:io';
    
    void main(){
      stdout.write("Enter your name : ");
      var name = stdin.readLineSync();
      stdout.write(name);
    }
    

    Output

    Enter your name : Jay
    Jay
    

    By default readLineSync() takes input as string. But If you want integer input then you have to use parse() or tryparse().

    0 讨论(0)
  • 2021-02-03 23:01

    The following should be the most up to date dart code to read input from stdin.

    import 'dart:async';
    import 'dart:io';
    import 'dart:convert';
    
    void main() {
      readLine().listen(processLine);
    }
    
    Stream<String> readLine() => stdin
        .transform(utf8.decoder)
        .transform(const LineSplitter());
    
    void processLine(String line) {
      print(line);
    }
    
    0 讨论(0)
提交回复
热议问题