User imput string int and float[DOUBT]

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 15 15:40:41 PST 2017


On 02/15/2017 03:20 PM, Jean Cesar wrote:
> How do I make a class person where I use set and get methods to imput
> the user type:

I have some information here:

   http://ddili.org/ders/d.en/input.html

You should also know how to read strings:

   http://ddili.org/ders/d.en/strings.html

And this section about refactoring has the concept of a readInt() 
function template:

   http://ddili.org/ders/d.en/functions.html#ix_functions.refactor

Combining all three:

import std.stdio;
import std.traits;

auto read(T)(ref T t, string message)
if (!isSomeString!T) {
     writef("%s: ", message);
     readf(" %s", &t);
     return t;
}

auto read(S)(ref S s, string message)
if (isSomeString!S) {
     import std.string : strip;
     writef("%s: ", message);
     s = readln().strip();
     return s;
}

class person
{
private:
     string name, address;
     int age;
     float height;

public:
     void setNome()
     {
         read(name, "Enter Your Name");
     }

     void setIty()
     {
         read(age, "Enter Your Age");
     }

     void setHeight()
     {
         read(height, "Enter Your Height");
     }

     float getHeight()
     {
         return height;
     }

     int getIty()
     {
         return age;
     }

     string getNome()
     {
         return name;
     }

}

void main ()
{
     person p = new person();

     p.setNome();
     p.setIty();
     p.setHeight();

     writeln(p.getNome());
     writeln(p.getIty());
     writeln(p.getHeight());
}

Unrelated, a bunch of get/set methods is commonly seen as inferior to a 
design where another piece of code does the reading and makes the object 
after the fact:

person readPerson(File input) {
     // ... parse the input ...
     // Potentially, use the constructor:
     auto p = new person(name, age, /* ... */);
     return p;
}

One reason is the fact that the person may be seen as incomplete and 
unusable unless all fields are set. Again, it's beside the point... :)

Ali



More information about the Digitalmars-d-learn mailing list