I'm writing a program in D that doesn't need a GUI. I remember that in C++, there was a way to remove a number of characters from console/terminal, but I don't know how to do this in D.
How do I remove a number of characters from the console/terminal?
(This didn't fit into a comment and I think it's what you are referring to)
Do you mean getchar? You have direct access to the entire standard C library in D. For example have a look at this simple script:
void main()
{
import core.stdc.stdio : getchar;
foreach(i; 0..3)
getchar();
import std.stdio;
writeln(readln());
}
When you compile & execute this script (e.g. here with rdmd)
echo "Hello world" | rdmd main.d
it would print:
lo world
But I have to agree with Adam that just slicing readln is easier and looks nicer ;-)
Related
I would like to know why when I execute the command go run example.go the won't print anything on terminal.
The code below works.
package main
import "fmt"
func main() {
fmt.Println("Hello")
}
Will print Hello.
But when I would like to use the function fmt.Printf when I run the command to execute, appear very quickly the response but is deleted on terminal.
package main
import "fmt"
func main() {
var i int = 2
fmt.Printf("%v %T", i, i) // fmt.Print does not work to
}
You use fmt.Printf with a format that does not end with a newline, so your system dutifully prints out the output without a terminating newline.
Presumably your shell then overwrites the output by sending the cursor to the beginning of the line and printing something. To prevent this from happening, either have your program end its output with a newline, or update your shell's prompt to avoid printing over existing output.
(Side note: it's just Go, not Go Lang. This goes give some issues with searching, common among short-named languages like C and C++.)
When Printf is used, you need to put a \n at the end.
Your program will produce undefined: I.
By replacing I with i it should work https://play.golang.org/p/GxFh-SYePR3 and return 2 int.
I'm experimenting with cgo to use C code from golang, but in my little hello-world test, I've ran into something I can't understand or find more information about.
I'm starting with a simple test similar to examples I've found
package main
import (
"fmt"
"unsafe"
)
/*
#import <stdio.h>
#import <stdlib.h>
*/
import "C"
func main() {
go2c := "Printed from C.puts"
var cstr *C.char = C.CString(go2c)
defer C.free(unsafe.Pointer(cstr))
C.puts(cstr)
fmt.Printf("Printed from golang fmt\n")
}
This simple example just echoes strings to stdout from both golang (using fmt.Printf) and raw C (using C.puts) via the basic cgo binding.
When I run this directly in my terminal, I see both lines:
$ ./main
Printed from C.puts
Printed from golang fmt
When I run this but redirect output in any way – pipe to less, shell redirection to a file, etc – I only see golang's output:
./main | cat
Printed from golang fmt
What happens to the C.puts content when piping / redirecting?
Secondary questions: Is this a cgo quirk, or a c standard library quirk I'm not aware of? Is this behaviour documented? How would I go about debugging this on my own (e.g. is there a good/plausible way for me to 'inspect' what FD1 really is in each block?)
Update: If it's relevant, I'm using go version go1.6.2 darwin/amd64.
This is C behavior you're seeing.
Go does not buffer stdout, while in C it is usually buffered. When the C library detects stdout is a tty, it may use line buffering, so the additional \n inserted by puts will cause the output to be displayed.
You need to flush stdout to ensure you get all the output:
go2c := "Printed from C.puts"
var cstr *C.char = C.CString(go2c)
defer C.free(unsafe.Pointer(cstr))
C.puts(cstr)
C.fflush(C.stdout)
fmt.Printf("Printed from golang fmt\n")
See also
Why does printf not flush after the call unless a newline is in the format string?
Is stdout line buffered, unbuffered or indeterminate by default?
The C library buffering is per line, so the first line can be left in the buffer before it is properly flushed (done at exit time in C programs). You can either try to flush stdout, or try adding a trailing \n in the first string. Does it work if you add the \n?
I would like to write a short d program that fills the screen with pound symbols. Here is what I have
import std.stdio;
import std.process;
import std.conv;
void main(string[] args){
auto lines = environment.get("LINES");
int line_count = to!int(lines);
for(int a = 1; a <= line_count; a++){
writeln("######################################################################");
}
}
I expected this to work because when I execute "echo $LINES" from the terminal it prints "47". However, LINES appears empty when I run the program via rdmd in the same session. This is on Ubuntu Raring. Any ideas?
If you can grab the output of the command stty size, that's probably more reliable than examining the $LINES and $COLUMNS environment variables.
Or you can invoke the TIOCGWINSZ ioctl as described in this answer.
If you just want a simple fix, you can put export LINES COLUMNS in your ~/.bashrc to make these variables available in your program.
For a proper solution, you could try to invoke the ioctl TIOCGWINSZ, or find a D library that supports querying the terminal (such as ncurses wrappers).
Back Story: In an attempt to better understand Haskell and functional programming, I've given myself a few assignments. My first assignment is to make a program that can look through a data set (a set of numbers, words in a blog, etc), search for patterns or repetitions, group them, and report them.
Sounds easy enough. :)
Question: I'd like for the program to start by creating a list variable from the data in a text file. I'm familiar with the readFile function, but I was wondering if there was a more elegant way to input data.
For example, I'd like to allow the user to type something like this in the command line to load the program and the data set.
./haskellprogram textfile.txt
Is there a function that will allow this?
import System.Environment
main :: IO ()
main = do
args <- getArgs
-- args is a list of arguments
if null args
then putStrLn "usage: ./haskellprogram textfile.txt"
else do contents <- readFile $ head args
putStrLn $ doSomething contents
doSomething :: String -> String
doSomething = reverse
That should be enough to get you started. Now replace reverse with something more valuable :)
Speaking of parsing some input data, you might consider breaking your data into lines or words using respective functions from Prelude.
You're looking for getArgs function.
Subtle Array, I can never resist mentioning my favorite when I was first learning Haskell, interact:
module Main where
main = interact doSomething
doSomething :: String -> String
doSomething xs = reverse xs
you then use it as cat textfile.txt | ./haskellprogram | grep otto or whatever. There is also a variant in Data.Text which you might get to know, and a few others in other string-ish libraries.
Playing with the relatively new ReadArgs package:
{-# LANGUAGE ScopedTypeVariables #-}
import ReadArgs (readArgs)
main = do
(fname :: String, foo :: Int) <- readArgs
putStrLn fname
Testing...
$ runhaskell args.hs blahblah 3
blahblah
One irritation with readArgs is that it doesn't work if you have only a single argument. Hmmm...
Once you have the desired file name as a String, you can use readFile as usual.
I have read about here documents on the book "The Ruby Programming Language" and didn't understand what is the purpose of here documents and when will you use it on production code. I would be happy if someone can explain and give some examples of usage.
regards,
In any language that supports them, a heredoc is a convenient way to make a large string literal.
Take the following contrived Ruby script that takes your name and outputs source code for a C program that tells you hello:
#!/usr/bin/env ruby
name = $*[0]
unless name
$stderr.puts "Please supply a name as the first argument to the program"
exit 1
end
source = <<EOF
#include <stdio.h>
int main()
{
puts("Hello, #{name}!");
return 0;
}
EOF
puts source
Other than a heredoc, the other option to make the source is to specify it line-by-line, which becomes tedious and potentially error prone (especially when you have embedded quotes).