CodeBlanks Logo Icon CodeBlanks

stdin/stdout

Learn I/O with stdin and stdout.

stdin and stdout

stdin and stdout are the input/output objects in Dart's dart:io library. stdin.readLineSync() reads a line from the user; stdout.writeln('msg') prints a line to the screen.

Example: stdout.write('Name: '); final name = stdin.readLineSync(); stdout.writeln('Hello $name');. This asks the user for a name and prints a greeting. It is used for interactive input in CLI applications. readLineSync is synchronous; it waits until a line arrives.

Interactive input

A CLI tool talks to the user: it asks a question, waits for an answer, then acts. You print the question with stdout.write('Question: ') and read the answer with stdin.readLineSync(). The answer comes as a String? so you can give a default with ??.

Example: final name = stdin.readLineSync() ?? 'Guest';. If the user enters nothing or input ends, 'Guest' is used. This makes CLI tools resilient; unexpected input becomes a default instead of a crash.

Practice Print with stdout

Add import 'dart:io';. Define a function readName that calls stdout.write('Name: ') and returns stdin.readLineSync() ?? 'Guest'. In main set final name = 'Ayşe'; and print with stdout.writeln('Hello $name').

Starter code

main.dart
// import the dart:io library
// define readName (write output + read input)

void main() {
  // print output with a fixed name
}

Sample solution

main.dart
import 'dart:io';

String readName() {
  stdout.write('Name: ');
  return stdin.readLineSync() ?? 'Guest';
}

void main() {
  final name = 'Ayşe';
  stdout.writeln('Hello $name');
}

Expected output

Hello Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the stdin/stdout parts

Term Meaning
stdin Input
stdout Output
readLineSync Reads a line
writeln Writes a line

2 What does stdin.readLineSync return?

  • double
  • bool
  • String? Correct answer
  • int

Explanation: stdin.readLineSync returns String?.

3 The readLineSync call

Question
String readName() {
  stdout.write('Name: ');
  return stdin.____() ?? 'Guest';
}
Answer
String readName() {
  stdout.write('Name: ');
  return stdin.readLineSync() ?? 'Guest';
}

Explanation: stdin.readLineSync() reads a line from the user.

All lessons in Advanced