Standard Input in Dart:
In Dart programming language, you can take standard input from the user through the console via the use of .readLineSync() function. To take input from the console you need to import a library, named dart:io from libraries of Dart.
About Stdin Class:
This class allows the user to read data from standard input in both synchronous and asynchronous ways. The method readLineSync() is one of the methods used to take input from the user. Refer to the official doc for other methods, from here.
Taking a string input from user:
Dart
import 'dart:io' ;
void main()
{
print( "Enter your name?" );
String? name = stdin.readLineSync();
print( "Hello, $name! \nWelcome to GeeksforGeeks!!" );
}
|
Input:
Geek
Output:
Enter your name?
Hello, Geek!
Welcome to GeeksforGeeks!!
Taking integer value as input:
Dart
import 'dart:io' ;
void main()
{
print( "Enter your favourite number:" );
int ? n = int .parse(stdin.readLineSync()!);
print( "Your favourite number is $n" );
}
|
Input:
01
Output:
Enter your favourite number:
Your favourite number is 1
Standard Output in Dart:
In dart, there are two ways to display output in the console:
- Using print statement.
- Using stdout.write() statement.
Printing Output in two different ways:
Dart
import 'dart:io' ;
void main()
{
print( "Welcome to GeeksforGeeks! // printing from print statement" );
stdout.write( "Welcome to GeeksforGeeks! // printing from stdout.write()" );
}
|
Output:
Welcome to GeeksforGeeks! // printing from print statement
Welcome to GeeksforGeeks! // printing from stdout.write()
Note:
The print() statement brings the cursor to next line while stdout.write() don’t bring the cursor to the next line, it remains in the same line.
If the print statements are switched in the above program then:
Output:
Welcome to GeeksforGeeks! // printing from stdout.write()Welcome to GeeksforGeeks! // printing from print statement
Making a simple addition program:
Dart
import 'dart:io' ;
void main()
{
print( "-----------GeeksForGeeks-----------" );
print( "Enter first number" );
int ? n1 = int .parse(stdin.readLineSync()!);
print( "Enter second number" );
int ? n2 = int .parse(stdin.readLineSync()!);
int sum = n1 + n2;
print( "Sum is $sum" );
}
|
Input:
11
12
Output:
-----------GeeksForGeeks-----------
Enter first number
Enter second number
Sum is 23