please correct my char count program...
Daniel Keep
daniel.keep.lists at gmail.com
Tue Jun 19 19:06:46 PDT 2007
import std.stdio : readln, writef, writefln;
void main()
{
writef("Please input your text: ");
auto s = readln();
writefln("Your text length is: %s", s.length);
}
Note that strings in D are *not* NUL-terminated like they are in C.
Your code wouldn't work since the .length of a char[100] is *always*
100. The following is untested, but should work:
import std.string : toString;
void main()
{
char[100] c_string_buffer;
scanf("%s", c_string_buffer.ptr);
auto d_string = toString(c_string_buffer.ptr);
}
.ptr gives you a pointer to an array's first element, so (char[100]).ptr
is a char*.
In this case, toString(char*) assumes its argument is a C-style
NUL-terminated string, and converts it to a D string. Note that it will
return a slice of the input data, so that in this particular case,
d_string must not outlive c_string_buffer.
-- Daniel
More information about the Digitalmars-d-learn
mailing list