#c++ code
const char buf[] = "I'm a newbie";
string s = buf;
printf(s.c_str());
#------
#nim code
#Is there any similar operation in nim? These are just my imagination.
var buf:seq[char] = "I'm newbiew"
buf = "have module?"
var str:string = buf
var buf2 = str.toSeq[char]()
Your code would be something like:
var buf: string = "I'm newbiew"
buf = "have module?"
echo buf
You can find more information here:
http://nim-lang.org/learn.html
http://nim-lang.org/docs/tut1.html
http://nim-by-example.github.io/
How to convert to string if I use seq[char] at first? I just want to know if there are any easy way.
var buf = newSeq[char](100)
buf[0] = '1'
buf[1] = '2'
...
#If I use seq before,I wan assign to string now, must use for cyclic?
#var str:string = buf #this is can't use.
var str:string = ""
for c in 0..high(buf):
str &= c
I'm sorry, My English is not good, so q is not clear. What @Araq said... afaik you could only do something like this and thats not very efficient.
proc seqToString(s: seq[char]): string =
result = newString(len(s))
for i,c in s:
result[i]=c
var buf = newSeq[char](100)
buf[0] = '1'
buf[1] = '2'
echo buf.seqToString
for i,c in s: result[i]=c
I would really expect something like:
for c in s: result << c
Can not find it yet. Is there a good reason not having a char append to string?
Something like this then?
let fh = open("/etc/hosts")
var buf = newString(100)
discard readBuffer(fh, cast[pointer](addr buf[0]), 10)
echo buf
unsafe and dangerous but works :)
import typetraits # for x.type.name
var sequ = @['h', 'e', 'l', 'l', 'o']
sequ.add('!')
echo sequ.type.name
echo sequ
let str = cast[cstring](addr(sequ[0]))
echo str.type.name
echo str
Note that this depends on the fact that the memory in the seq is laid out sequentially. I don't know whether this is guaranteed or not - in a C++ vector is is guaranteed, but one could imagine a linked list or something used by seq (like by python's lists).
So what does this do?
proc toString(sequ: var seq[char]): string =
$cast[cstring](addr(sequ[0]))
let x = sequ.toString
echo x.type.name
echo x
So, as the others have said, there is probably a better way to do what you want to do, but Nim is flexible enough to just do a low-level C cast if you need to.
readAll(file) can solve it, In fact, I just want to ask if there is a simpler way (seq or array to string). :)
Oh, Thanks jdm, I just don't know how to display type name, know now and your module is very good! The cstring can be used as a pointer (like c char*).
You could also use the streams interface: http://nim-lang.org/docs/streams.html
proc readStr(s: Stream; length: int): TaintedString {.raises: [Exception],
tags: [ReadIOEffect].}
reads a string of length length from the stream s. Raises EIO if an error occurred.
let fs = newFileStream("/etc/hosts", fmRead)
let s = fs.readStr(10)
echo s
I would really expect something like:
> for c in s:
> result << c
> Can not find it yet.
system.add works for single chars too.