please correct my char count program...

Derek Parnell derek at nomail.afraid.org
Tue Jun 19 19:18:55 PDT 2007


On Tue, 19 Jun 2007 21:48:06 -0400, pieter Valdano pattiruhu wrote:

> here is my count char program:
> 
> import std.stdio;
> import std.string;
> 
> void main()
> {
>      char* s;
>      char string[100];
> 
> writef("please input your text=");
> scanf("%s",&string);
> writef("your text length is=",string.length);
> }

The main problem is that you are trying to write D as if it was C. There
are large differences that make D coding a whole lot easier. 

For example, here is a way of doing it :

  import std.stdio;

  void main()
  {
    char[] s;

    writef("please input your text=");
    s = readln();
    writef("your text length is=",s.length);
  }

The differences are that D can use a variable-length array rather than a
fixed-length one that one typically uses in C. Also in D, it is rare to use
pointers such as 'char *p' because it knows a lot more about arrays and
pointer usage than C does, which means you don't have to code as much.

Note that when readln() runs, it collects all the characters typed
including the Return/Enter key so that the last character in the buffer is
always '\n'.


-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
20/06/2007 12:13:29 PM


More information about the Digitalmars-d-learn mailing list