Markus Loecher
Markus Loecher

Reputation: 378

readChar from stdin

I would like to read in one character at a time and convert it to a string command to execute once a space is entered. I tried

con <- file("stdin")
open(con, blocking=TRUE)
while(q!=" "){
  #q=scan("",what="", nmax=1)
  q=readChar(con,1)
  cmd[i]=q;i=i+1
}
eval(cmd)

but I seem to not understand readChar() correctly.

Upvotes: 2

Views: 692

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368439

Interesting question, but with a few flaws:

  • you use q, cmd and i and never assign them which leads to immediate error and program abort on undefined symbols being used in tests or assignments
  • you test for q at the top of your while loop but never give it a value (related to previous point)
  • you assign in the vector with i but never set to 1 first
  • you misunderstand how string concatenation works
  • you misunderstand how input from the console works, it is fundamentally by line and not by character so your approach has a deadly design issue (and blocking makes no difference)
  • you terminate the wrong way; your sentinel value of '' still gets assigned.
  • you open a console and never close it (though that may be ok with stdin)
  • you grow the result var the wrong way, but that doesn't matter here compared to all the other issues

If we repair the code a little, and use better style with whitespaces, no semicolons and an <- for assignment (all personal / common preferences) we get

con <- file("stdin")
open(con, blocking=TRUE)
cmd <- q <- ""
i <- 1
while (q != " ") {
    q <- readChar(con,1)
    cmd[i] <- q
    i <- i+1
}
print(cmd)  # for exposition only
close(con)

and note the final print rather than eval, we get this (and I typed the ls command letters followed by whitespace)

$ Rscript /tmp/marcusloecher.R
ls 
[1] "l" "s" " "
$ 

I suggest you look into readLines() instead.

And now that I checked, I see that apparently you also never accept an answer to questions you asked. That is an ... interesting outcome for someone from our field which sometimes defines itself as being all about incentives...

Upvotes: 4

Related Questions