How do I read console input / stdin in Dart?

旧时模样 提交于 2020-12-28 06:50:50

问题


How do I read console input from stdin in Dart?

Is there a scanf in Dart?


回答1:


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 :(');
}



回答2:


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);
}



回答3:


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().




回答4:


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. */);


}


来源:https://stackoverflow.com/questions/11122732/how-do-i-read-console-input-stdin-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!