How to emulate scanf in dart?
I want to translate the following C code into dart.
#include <stdio.h>
void main() {
double a,b;
printf("a b? ");
scanf("%lf%lf",&a,&b);
printf("a=%lf b=%lf\n",a,b);
}
As I know, I cannot use call by reference, variable number arguments function call or destructuring assignment in dart.
So, it seems that it is impossible to make a function emulating scanf for now.
Here is my version in dart.
import "dart:io";
void main() {
stdout.write("a b? ");
var line = stdin.readLineSync();
var tokens = line?.split(RegExp(r'\s+'));
double a = double.tryParse(tokens?[0] ?? '0') ?? 0;
double b = double.tryParse(tokens?[1] ?? '0') ?? 0;
print("a=$a b=$b");
}
In there any possible improvement in the code?
Here is another version using Iterator.
import 'dart:io';
void main() {
stdout.write("a b? ");
var scan = Scan();
var a = scan.getDouble();
var b = scan.getInt();
print("a=$a b=$b");
}
class Scan {
Iterator? it;
Scan([String? line]) {
it = (line ?? stdin.readLineSync())?.split(RegExp(r'\s+')).iterator;
}
double getDouble() {
return double.tryParse(it?.moveNext() == true ? it?.current : '') ?? 0;
}
int getInt() {
return int.tryParse(it?.moveNext() == true ? it?.current : '') ?? 0;
}
}
I want to get integer input from console in dart but unable to do so . How do I do that?
main()
{
int n = stdin.readLineSync();
}
You need to parse string captured by stdin.readLineSync() using int.parse()
import 'dart:io';
void main() {
int n = int.parse(stdin.readLineSync());
}
I am very new to java as I have only started yesterday and I am trying to make a little game where a random number is generated and you have to try to guess that number. The problem I am having right now is nothing will come out of the console. I am not sure what is causing this as it might be the code or the interpreter I am using. Here is the code for you guys to check over. Let me know what I did wrong and if you can find a fix, thanks.
import java.util.Scanner;
public class Random
{
int Ran = (int) Math.floor(Math.random() * 9);
Scanner input = new Scanner(System.in);
int Num = input.nextInt();
public static void main(String[] args){}
{System.out.println("Geuss a number and see if it is correct!");
}
{
if (Num == Ran)
{System.out.println("Correct! The number was " + Ran);
}
else{
System.out.println("You are wrong!");
}
}
public void If(boolean b) {}
}
you have empty{}
public static void main(String[] args){
System.out.println("Geuss a number and see if it is correct!");
}
Also do not write IF as a function. If is native expression in native coding.
There is already if clause so try to give unique names.
import java.util.Scanner;
public class Random
{
int Ran = (int) Math.floor(Math.random() * 9);
Scanner input = new Scanner(System.in);
int Num = input.nextInt();
public static void main(String[] args)
{
System.out.println("Geuss a number and see if it is correct!");
if (Num == Ran)
{System.out.println("Correct! The number was " + Ran);
}
else{
System.out.println("You are wrong!");
}
}
}
try this.
import java.util.Scanner;
public class Random
{
int Ran = (int) Math.floor(Math.random() * 9);
Scanner input = new Scanner(System.in);
int Num = input.nextInt();
public static void main(String[] args){
System.out.println("Geuss a number and see if it is correct!");
if (Num == Ran)
{System.out.println("Correct! The number was " + Ran);
}
else{
System.out.println("You are wrong!");
}
}
public void If(boolean b) {}
}
}
import 'dart:math';
import 'dart:io';
void main() {
int guess;
Random rand = new Random(); //create a random number generator
int answer = rand.nextInt(100); //gets a random integer from 0 to 99 do {
print("Enter your guess:");
String temp = stdin.readLineSync(); //read in from the keyboard guess = int.parse(temp); //convert String to integer
if (guess < answer) {
print("Too low!");
} else if (guess > answer) {
print("Too high!");
}
}
while (guess != answer);
print("You got it!");
}
What is wrong?? I deleted the } in
} while (guess != answer);
print("You got it!");
and now in the console it says
Enter your guess:
32
Breaking on exception: object of type NoSuchMethodError
Your guess variable is always null as it's never assigned (it's commented out), try changing your code to:
import 'dart:math';
import 'dart:io';
void main() {
int guess;
Random rand = new Random(); //create a random number generator
int answer = rand.nextInt(100); //gets a random integer from 0 to 99
do {
print("Enter your guess:");
String temp = stdin.readLineSync(); //read in from the keyboard
guess = int.parse(temp); //convert String to integer <-- the assignment is what's missing here
if (guess < answer) {
print("Too low!");
} else if (guess > answer) {
print("Too high!");
}
} while (guess != answer);
print("You got it!");
}
There is a related issue with the readLineSync here which you might want to have a look.
I guess it is because guess is null and null has no >/< operator.
guess is null because you never assign a value.
If guess and answer are not equal this makes a perfect endless loop:
while (guess != answer);
print("You got it!");
}
Wow I failed. Man im tired seems I was typing way to sloppy/fast and left some of my code in the comments :( found it right after seeing this post sigh.. this is the correct working code
import 'dart:math';
import 'dart:io';
void main() {
int guess;
Random rand = new Random(); //create a random number generator
int answer = rand.nextInt(100); //gets a random integer from 0 to 99
do {
print("Enter your guess:");
String temp = stdin.readLineSync(); //read in from the keyboard
guess = int.parse(temp); //convert String to integer
if (guess < answer) {
print("Too low!");
} else if (guess > answer) {
print("Too high!");
}
}
while (guess != answer);
print("You got it!");
}
Thats enough learning of Dart for today. Thanks everyone for the quick replies seems the Dart community is active!
im off to bed! have a great day
How do I read console input from stdin in Dart?
Is there a scanf in Dart?
The readLineSync() method of stdin allows to capture a String from the console:
import 'dart:convert';
import 'dart:io';
void main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: utf8);
print(line?.trim() == '2' ? 'Yup!' : 'Nope :(');
}
Old version:
import 'dart:io';
main() {
print('1 + 1 = ...');
var line = stdin.readLineSync(encoding: Encoding.getByName('utf-8'));
print(line.trim() == '2' ? 'Yup!' : 'Nope :(');
}
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);
}
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().
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. */);
}
As of Dart 2.12, null-safety is enabled, and stdin.readLineSync() now returns a String? instead of a String.
This apparently has been confusing a lot of people. I highly recommend reading https://dart.dev/null-safety/understanding-null-safety to understand what null-safety means.
For stdin.readLineSync() specifically, you can resolve this by checking for null first, which for local variables will automatically promote a String? to a String. Here are some examples:
// Read a line and try to parse it as an integer.
String? line = stdin.readLineSync();
if (line != null) {
int? num = int.tryParse(line); // No more error about `String?`.
if (num != null) {
// Do something with `num`...
}
}
// Read lines from `stdin` until EOF is reached, storing them in a `List<String>`.
var lines = <String>[];
while (true) {
var line = stdin.readLineSync();
if (line == null) {
break;
}
lines.add(line); // No more error about `String?`.
}
// Read a line. If EOF is reached, treat it as an empty string.
String line = stdin.readLineSync() ?? '';
Note that you should not blindly do stdin.readLineSync()!. readLineSync returns a String? for a reason: it returns null when there is no more input. Using the null assertion operator (!) is asking for a runtime exception.
Note that while calling stdin.readLineSync() your isolate/thread will be blocked, no other Future will be completed.
If you want to read a stdin String line asynchronously, avoiding isolate/thread block, this is the way:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// [stdin] as a broadcast [Stream] of lines.
Stream<String> _stdinLineStreamBroadcaster = stdin
.transform(utf8.decoder)
.transform(const LineSplitter()).asBroadcastStream() ;
/// Reads a single line from [stdin] asynchronously.
Future<String> _readStdinLine() async {
var lineCompleter = Completer<String>();
var listener = _stdinLineStreamBroadcaster.listen((line) {
if (!lineCompleter.isCompleted) {
lineCompleter.complete(line);
}
});
return lineCompleter.future.then((line) {
listener.cancel();
return line ;
});
}
All these async API readLine*() based solutions miss the syntactic sugar which gives you the ability to do everything without synchronous blocking, but written like synchronous code. This is even more intuitive coming from other languages where you write code to execute synchronously:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
var lines = stdin.transform(utf8.decoder).transform(const LineSplitter());
await for (final l in lines) {
print(l);
}
print("done");
}
The key takeaway here is to make use of async and await:
async on your method is required, as you're using await to interface with asynchronous API calls
await for is the syntax for doing "synchronous-like" code on a Stream (the corresponding syntax for a Future is just await).
Think of await like "unwrapping" a Stream/Future for you by making the following code execute once something is available to be handled. Now you're no longer blocking your main thread (Isolate) to do the work.
For more information, see the Dart codelab on async/await.
(Sidenote: The correct way to declare any return value for an async function is to wrap it in a Future, hence Future<void> here.)
You can use the following line to read a string from the user:
String str = stdin.readLineSync();
OR the following line to read a number
int n = int.parse(stdin.readLineSync());
Consider the following example:
import 'dart:io'; // we need this to use stdin
void main()
{
// reading the user name
print("Enter your name, please: ");
String name = stdin.readLineSync();
// reading the user age
print("Enter your age, please: ");
int age = int.parse(stdin.readLineSync());
// Printing the data
print("Hello, $name!, Your age is: $age");
/* OR print in this way
* stdout.write("Hello, $name!, Your age is: $age");
* */
}
You could of course just use the dcli package and it's ask function
Import 'package: dcli/dcli.dart':
Var answer = ask('enter your name');
print (name);
Use the named validator argument to restrict input to integers.
To read from the console or terminal in Dart, you need to:
import 'dart:io' library
store the entered value using stdin.readLineSync()!
parse the input into an int using int.parse(input) if necessary
Code:
import 'dart:io';
void main() {
String? string;
var number;
stdout.writeln("Enter a String: ");
string = stdin.readLineSync()!;
stdout.writeln("Enter a number: ");
number = int.parse(stdin.readLineSync()!);
}