www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Input handling? (newbie alert!)

reply Cavalary <cavalary1684 hotmail.com> writes:
Now I guess this has been asked and answered 1000 times before
around here, but looking through discussions that don't even seem
to thread properly (unless you're in the archive) would just
confuse me more, and the few attempts at D tutorials for people
who are not already skilled C++ programmers didn't help me much
with anything either, so:
How exactly do you handle user input in D? Particularly, are there
functions that automatically catch/handle type errors (as in you
ask for an integer and the user enters a string)? And, uh, how do
you deal with inputting strings? Because all I tried compiled fine
but only got me access violations when ran.

Just to stress that newbie alert I mentioned: Only been fooling
around with D for a day and a half, so my current level of
knowledge is only above 0 if you have lots of decimals.
Also been fooling with Ruby for 3 days (or 2 really, because I
didn't do anything in it yesterday), which leads to these examples:

Ruby code (can't break it, if you enter floats it just rounds
down, if you enter non-numbers it just assumes zero, so no errors):

arr = []
print("How many numbers? ")
num = gets.chomp.to_i
i = 0
while i < num
 print("Enter number #{i + 1}: ")
 arr[i] = gets.chomp.to_i
 i = i + 1
end
puts("The length of arr is #{arr.length}.")
puts("arr contains: #{arr.join(", ")}.")

D code (only works as long as the user plays nice):

import std.stdio;
void main() {
 int[] arr;
 int num;
 write("How many numbers? ");
 scanf("%d", &num);
 arr.length = num;
 foreach (i; 0 .. num) {
  writef("Enter number %d: ", i + 1);
  scanf("%d", &arr[i]); }
 writefln("The length of arr is %d.", arr.length);
 write("arr contains: ");
 foreach (i; 0 .. (arr.length - 1)) {
  writef("%d, ", arr[i]); }
 writefln("%d.", arr[arr.length - 1]); }

(Started from that completely incorrect example in the "newbie-
oriented tutorial", which I fooled around with to take user input
after finding out how it actually works.
I'm sure it looks awful, but I'm just working with the few
commands I managed to pick up in both languages...)

As for strings, uh... Here, pieces of another test Ruby script:

$numeral = ['first', 'second']
$name = []
i = 0
$numeral.each do
 print("Enter #{$numeral[i]} name: ")
 name = gets.chomp
 $name.push name.capitalize
 i = i + 1
end
// Other stuff
i = 0
$name.each do
 puts("#{$name[i]}'s stats:")
 // Other stuff
 i = i + 1
end

How do I chomp in D? And how do I capitalize?
But more importantly, how do I make it read strings without giving
access violations? scanf("%s", &name[i]); certainly doesn't work...

Yeah, I know I babble, so if you could just point me to a nicely
written and accurate D tutorial that assumes no prior C++ (or
similar) knowledge whatsoever, I'll stop pestering you...
Sep 09 2010
next sibling parent reply Bernard Helyer <b.helyer gmail.com> writes:
I've not time for a more full answer now (I'll try later), but please, 
for the love of God, don't use scanf! As a general hint, use 
std.stdio.readln to get input as a string, then use the `to` function 
found in std.conv to convert it into what you want:

   auto input = readln();
   auto asInteger = to!int(input);

To handle errors, you'll probably want to catch whatever it is that to 
throws on failure:

   int i;
   auto input = readln();
   try {
       i = to!int(input);
   } catch (TheThingThatToThrows) {
       i = 0;
   }

I don't know how to!int handles entry of floating point numbers, if it 
doesn't, what you may want to do:

    int i;
    auto input = readln();
    try {
        i = cast(int) to!double(input);
    } catch (TheThingThatToThrows) {
        i = 0;
    }

---

Sorry I couldn't be more thorough. I hope that helps!
Sep 09 2010
next sibling parent reply Jonathan M Davis <jmdavisprog gmail.com> writes:
On Thursday 09 September 2010 17:48:47 Bernard Helyer wrote:
 I've not time for a more full answer now (I'll try later), but please,
 for the love of God, don't use scanf! As a general hint, use
 std.stdio.readln to get input as a string, then use the `to` function
 found in std.conv to convert it into what you want:
 
    auto input = readln();
    auto asInteger = to!int(input);
 
 To handle errors, you'll probably want to catch whatever it is that to
 throws on failure:
 
    int i;
    auto input = readln();
    try {
        i = to!int(input);
    } catch (TheThingThatToThrows) {
        i = 0;
    }
 
 I don't know how to!int handles entry of floating point numbers, if it
 doesn't, what you may want to do:
 
     int i;
     auto input = readln();
     try {
         i = cast(int) to!double(input);
     } catch (TheThingThatToThrows) {
         i = 0;
     }
 
 ---
 
 Sorry I couldn't be more thorough. I hope that helps!

Yes std.stdio.readln() would be a much better way to go. However, I'd suggest using std.conv.parse() rather than std.conv.to(). It's less picky about whitespace, and it allows you to deal with the case where you have multiple values on the same line. For string manipulation functions, check out the functions in std.string. - Jonathan M Davis
Sep 09 2010
parent reply Cavalary <cavalary1684 hotmail.com> writes:
Well, I was just looking through examples, and if those used scanf
I assumed that was the way to go...
Thanks, actually learned a few more things out of this (auto and
try). No idea what the parameter after catch is supposed to do,
what cast is or how to use parse since it was just mentioned, but
at least now I know what to look up info for :)

No idea what got into me to try to teach myself some programming
(and particularly something as advanced as D) these days. Haven't
coded something that compiled in some 9 years (and that was
Pascal, in 9th-10th grade). No scripting either in at least 5
(that's if staring in bewilderment at the Ruby code of an RPG
Maker XP project I was working on at the time even counts as
scripting). Only poked around with a little XHTML and CSS and took
a "let's see what happens if I change this" approach with the PHP
in my blog's theme, but not even that in some 2 years.
So not much of anything to base further learning on and a high
likelihood of saying I had enough and forgetting all about it
again if my mind will get twisted in knots over some concept, so
trying to be very "hands on" and putting away anything that
doesn't immediately make sense in hopes it will later. Let's see
if anything comes out of it :)
Sep 10 2010
next sibling parent reply bearophile <bearophileHUGS lycos.com> writes:
Cavalary:
 No idea what got into me to try to teach myself some programming
 (and particularly something as advanced as D) these days.

With D you may learn some ideas of informatics. Bye, bearophile
Sep 10 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
Jonathan M Davis:
 You mean computer science? That's the English term - in the US at least.

http://en.wikipedia.org/wiki/Informatics_%28academic_field%29 Most of "Computer Science" is not about computers, and most of it is not a science. It's more a cross between mathematics and engineering. Bye, bearophile
Sep 11 2010
parent reply Cavalary <cavalary1684 hotmail.com> writes:
Hm, to me "informatics" made sense :) Not sure if I ever heard it
used in English, but it sounds more suitable than "computer
science", which (no matter how it's officially used) sounds like
it would include everything that deals with computers, so hardware
as well.

As for what Jesse said, yeah, know that D is a stricter language,
and in many ways it makes sense, but sometimes you sure get to
wish for some more wiggle room. (Oh yeah, figured out what cast
did from a compiler error.)

Right now just managed to fully port into D my "toy" Ruby script
(which generates 2 randomized characters, which you get to name,
and has them duel it out in text, including a tiny AI moment
because each starts with a potion which they use when appropriate).
2 days ago I was staring at that code and didn't even know where
to begin porting it. I'm sure it's a really ugly job, but hey, it
runs! (The only difference being that Ruby round = D lround, but
that's apparently not implemented yet in D2.) So let's see what's
next.
And thanks again. Haven't seen readln() used in any of the
examples I glanced over, so would have had no idea about it
otherwise...
Sep 11 2010
next sibling parent reply Cavalary <cavalary1684 hotmail.com> writes:
Yeah, one of the reasons why it made sense to me I guess, as the
term's "informatica" in Romanian, so the mental link was instant
even if I probably never heard it used in English before.

A programming language that doesn't put effort into teaching
people how to use it isn't exactly likely to end up with a
significant userbase, don't you think? (As for D1, from my 1
attempt to compile my "toy" into it I know it can't handle
my "hybrid" use of foreach (just how it made sense to me when
porting from Ruby... and since it worked in D2, great).)
But yeah, starting to poke around through the Phobos docs and even
the files (when I looked for random number generators, when the
compiler announced that rand was deprecated, and also for the
rounding functions... "Hm? Undefined? If I were a rounding
function, where would I be? ... Math? Let's see what's in there
then.")

readln seems to do well enough for input for the moment. I'll be
looking into file I/O later.
Just put in my first working try-catch last night too. (After
scratching my head a lot because from the example I was given I
assumed catch needed a random parameter, though I didn't
understand why. Then the compiler errors made me try with no
parameter (as in catch()), variable types, the word "class",
either alone or followed by various things (since it said it only
accepted classes)... Eventually found a post in the learn archives
that said that if you want catch-all you just put in catch with no
parentheses and went duh!)

About seriousness... At the moment I don't even know if I'll still
have it installed next week. And I'll need to be REALLY serious
about something to shell out $40 on a book about it! And there's
also the matter of availability over here (though Andrei's name
says he was most likely at least born here).
Sep 12 2010
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
Cavalary wrote:

 Yeah, one of the reasons why it made sense to me I guess, as the
 term's "informatica" in Romanian

Getting back to the tutorial question, with the remote chance that you know Turkish as well, there is http://ddili.org/ders/d/index.html That tutorial still uses std.cstream (din.readf, etc.) though. I tried to convert it to stdin.readf but could not go far with 2.048. I am waiting for future releases with more novice-friendly standard input handling. Ali
Sep 14 2010
prev sibling parent reply bearophile <bearophileHUGS lycos.com> writes:
Jonathan M Davis:

 Informatics is essentially the term used in at least some European languages 
 other than English. Personally, I think that the name is no better - if not 
 worse - than computer science, since it implies that it has to do with the
study 
 of information, which doesn't necessarily have anything to do with computers, 
 math, or logic.

I think the term "Informatics" is better than "Computer Science" for this field we are talking about, because despite there are parts of math and logic that it doesn't cover, it does cover the part related to the management of information, its processing, storage, and transmission, that are large parts of this field. On the other hand "Computer Science" is mostly misleading, both words don't fit very well with what this field is.
 In any case, I was just pointing out to Bearophile that the official English
 term is computer science so that he's better able to communicate in English

English is something you learn and use, but it's also something created by people, so it's also something you can influence, grow, and improve. This is why it's positive for everyone to try to improve the language.
 (from this and other posts, I gather that English is not his first language,
 though he's definitely fluent).

Thank you :-) You are right, English is not my first language. My English grammar has some evident holes (The usage of 'can', 'may' and 'might' are one of the most evident ones, that I need to fill). My general linguistic skills are awful, the work I have done to learn some English is probably enough for your average human to learn three languages :-) I now know a bit of English just because I was stubbornly determined to learn it, no matter how much work. Bye, bearophile
Sep 12 2010
next sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
bearophile wrote:

 I think the term "Informatics" is better than "Computer Science" for this
 field we are talking about

On a related note, "programmers" are called "software engineers" in the US, at least in Silicon Valley.
 "Computer Science" is mostly misleading, both words don't fit very well
 with what this field is.

Agreed. About programming, I am pretty convinced that it is a craft more than anything else.
 My English grammar has some evident holes

I know that I am not kualified ;) to judge, but your English is just perfect. Ali
Sep 14 2010
prev sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Tuesday, September 14, 2010 10:41:53 Ali =C3=87ehreli wrote:
 bearophile wrote:
  > I think the term "Informatics" is better than "Computer Science" for
  > this field we are talking about
=20
 On a related note, "programmers" are called "software engineers" in the
 US, at least in Silicon Valley.

Well, software engineers are programmers, but programmers aren't necessaril= y=20 software engineers - just like there is a software engineering major in add= ition=20 to computer science. Their focus is different.
  > "Computer Science" is mostly misleading, both words don't fit very well
  > with what this field is.
=20
 Agreed. About programming, I am pretty convinced that it is a craft more
 than anything else.

I believe that the idea is that computer science is the study of computers = =2D=20 like how political science is the study of politics. However, computer scie= nce=20 only covers the software side of things, isn't entirely tied to a computer,= and=20 is really more like math or engineering (though when you focus on the=20 engineering side of things, you start straying into software engineering ra= ther=20 than computer science) rather than science, since (aside from debugging) it= =20 really has nothing to do with the scientific method. So, while the basic id= ea=20 behind the name is solid, it doesn't really fit very well when you get down= to=20 the details. =2D Jonathan M Davis
Sep 14 2010
prev sibling parent Jonathan M Davis <jmdavisprog gmail.com> writes:
On Friday 10 September 2010 09:47:47 bearophile wrote:
 Cavalary:
 No idea what got into me to try to teach myself some programming
 (and particularly something as advanced as D) these days.

With D you may learn some ideas of informatics. Bye, bearophile

You mean computer science? That's the English term - in the US at least. - Jonathan M Davis
Sep 10 2010
prev sibling parent Bernard Helyer <b.helyer gmail.com> writes:
On Thu, 09 Sep 2010 18:07:43 -0700, Jonathan M Davis wrote:
 Yes std.stdio.readln() would be a much better way to go. However, I'd
 suggest using std.conv.parse() rather than std.conv.to(). It's less
 picky about whitespace, and it allows you to deal with the case where
 you have multiple values on the same line. For string manipulation
 functions, check out the functions in std.string.
 
 - Jonathan M Davis

D'oh. I completely forgot that std.conv.parse existed! >_<;
Sep 09 2010
prev sibling next sibling parent Jonathan M Davis <jmdavisprog gmail.com> writes:
On Saturday 11 September 2010 08:51:11 bearophile wrote:
 Jonathan M Davis:
 You mean computer science? That's the English term - in the US at least.

http://en.wikipedia.org/wiki/Informatics_%28academic_field%29 Most of "Computer Science" is not about computers, and most of it is not a science. It's more a cross between mathematics and engineering. Bye, bearophile

I'm not necessarily saying that computer science is the best term for the field in question. It is, however, the official term. And I would hazard a guess that a large portion of programmers in the US won't even know what you mean if you use the term informatics. Most of them will likely think about bioinformatics, since the term is used. So, if you're looking to be clearly understood, computer science is the term to use. - Jonathan M Davis
Sep 11 2010
prev sibling next sibling parent Jonathan M Davis <jmdavisprog gmail.com> writes:
On Saturday 11 September 2010 13:54:19 Cavalary wrote:
 Hm, to me "informatics" made sense :) Not sure if I ever heard it
 used in English, but it sounds more suitable than "computer
 science", which (no matter how it's officially used) sounds like
 it would include everything that deals with computers, so hardware
 as well.

Informatics is essentially the term used in at least some European languages other than English. Personally, I think that the name is no better - if not worse - than computer science, since it implies that it has to do with the study of information, which doesn't necessarily have anything to do with computers, math, or logic. Apparently the term is already taken by more or less that anyway: http://en.wikipedia.org/wiki/Informatics_(academic_field) . But I've never heard a term which really properly captured what computer science / informatics is. All candidates have problems of one sort or another. In any case, I was just pointing out to Bearophile that the official English term is computer science so that he's better able to communicate in English (from this and other posts, I gather that English is not his first language, though he's definitely fluent). What the best term would technically be really isn't of consequence, since it's not like we really get to pick at this point.
 And thanks again. Haven't seen readln() used in any of the
 examples I glanced over, so would have had no idea about it
 otherwise...

The examples on D's site are generally both sparse and old. Many of the projects on dsource are either D1 and/or old, so it's not a great place to look for examples either. The reality of the matter at this point is that you're going to have to read through the Phobos docs if you want to find all of the functions which could be useful to you. Also, I think that many of the examples in the language documentation in particular (rather than the Phobos docs) are more likely to be C in style rather than taking advantage of more idiomatic D stuff like ranges. My guess is that that's because a fair bit of it was done by Walter rather than Andrei. In any case, good examples of D code are rather lacking at this point, so you'll have to explore the Phobos docs yourself and pay attention to what people post. For that matter, you could dive in the Phobos code and have a look there. std.range and std.algorithm are probably particularly good to look at - though neither would really help you with I/O. However, Andrei's recently published book "The D Programming Language" (typically referred to as TDPL around here) is a fantastic source for learning about D. So, if you haven't picked that up yet, I highly recommend it. It's the best introductory book to a programming language that I've ever read (probably in part because it doesn't assume that you've never programmed in your life and have no clue what basic stuff like variables or if statements are - it does explain how they work in D though). Howeve, t does mean shelling out around $40, so whether it's worth it depends on how serious you are about learning and using D. - Jonathan M Davis
Sep 11 2010
prev sibling parent Jonathan M Davis <jmdavisprog gmail.com> writes:
On Sunday 12 September 2010 04:18:01 Cavalary wrote:
 Yeah, one of the reasons why it made sense to me I guess, as the
 term's "informatica" in Romanian, so the mental link was instant
 even if I probably never heard it used in English before.
 
 A programming language that doesn't put effort into teaching
 people how to use it isn't exactly likely to end up with a
 significant userbase, don't you think?l

There are higher priorities at the moment. For the most part, the folks who would be working on examples and the like are busy on dmd, druntime, and/or phobos. While D and dmd have essentially stabilized now as far as features go, there's plenty of bug fixing to do, and Walter is busy on things like the port to 64 bit and making shared libraries work. And more importantly, yhobos is still very much a work in progress, so while much of it is going to stay the way that it is more or less permanently, there's plenty of it which is still in flux, so it doesn't make a lot of sense to create a whole lot of examples using it. As it matures, I'm sure that there will be more example code, but it's still pretty young at this point.
 readln seems to do well enough for input for the moment. I'll be
 looking into file I/O later.
 Just put in my first working try-catch last night too. (After
 scratching my head a lot because from the example I was given I
 assumed catch needed a random parameter, though I didn't
 understand why. Then the compiler errors made me try with no
 parameter (as in catch()), variable types, the word "class",
 either alone or followed by various things (since it said it only
 accepted classes)... Eventually found a post in the learn archives
 that said that if you want catch-all you just put in catch with no
 parentheses and went duh!)

Typicall what you'd do is use catch(Exception e), so you can do things like print the exception, but catch without parens will work (you just don't have access to the exception).
 About seriousness... At the moment I don't even know if I'll still
 have it installed next week. And I'll need to be REALLY serious
 about something to shell out $40 on a book about it! And there's
 also the matter of availability over here (though Andrei's name
 says he was most likely at least born here).

That's totally understandable. However, since D2 has recently become essentially stable feature-wise (as in within the last few months), TDPL is pretty much _the_ source for anything in-depth on D (though, as phobos isn't particularly mature yet, it doesn't cover much of phobos). As time goes on, I'm sure that online resources will improve, but D has been in flux for so long as it's been being developed, that online examples and the like tend to be out of date or nonexistent. With time, that will change though. As for availability, I don't know the best way to get it in Romania, but I know that folks in Europe have ordered it from Amazon without any problems. And while I don't know if Andrei was born in Romania, as I understand it, he does have family there, and he has an accent, so he probably was. - Jonathan M Davis
Sep 12 2010