Lellansin / node-scanf

C like scanf module for node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to detect EOF?

XiaoPanPanKevinPan opened this issue · comments

I'm a newbie, so if this question is dumb, I'm sorry.

I don't know how to detect if it's the end of the input. For example, if I have a file called data.txt:

2 1 1
1 2 2
2 2 3
1 2 5

And a code main.mjs:

import { default as scanf, sscanf } from "scanf";

let a, b, c;
while(([a, b, c] = scanf("%d %d %d"))) { // don't know when to stop
        console.log(a, b, c);
}

After calling node main.mjs < data.txt

It results in infinite output:

2 1 1
1 2 2
2 2 3
1 2 5
2 1 1
1 2 2
2 2 3
1 2 5
2 1 1
1 2 2
2 2 3
1 2 5
// ... omitted

As the title, is there any way to detect that?

@XiaoPanPanKevinPan Hi Kevin, to detect the end of the input in your scenario, you can modify your code to check for the return value of the scanf function. If it returns null, it means there is no more input to match, and you can break the loop.

for example:

we can change the code to:

const scanf = require('scanf');

let a, b, c;
while(([a, b, c] = scanf("%d %d %d"))) { // don't know when to stop
  console.log(a, b, c);
  if (!a || !b || !c) break; // break the loop
}

console.log('over.');
node test.js
1 2 3
1 2 3
1 2 test  # <---- any non-numeric words
1 2 NaN
over.

or

2021 2022 2023
2021 2022 2023
over           # enter
               # enter
               # enter
NaN null null
over.

If you are ok to making modifications to this scenario, it can be changed to:

const scanf = require('scanf');

const list = [];
let a;
while((a = scanf("%d"))) {
  console.log(a);
  if (!a) break;
  list.push(a);
}

console.log('list =', list);

and test would be like:

$ node test.js
1 2 3       # type numbers with enter
1
2
3
4 5 6
4
5
6
over
list = [ 1, 2, 3, 4, 5, 6 ]