Jump to page: 1 2
Thread overview
Input handling? (newbie alert!)
Sep 09, 2010
Cavalary
Sep 10, 2010
Bernard Helyer
Sep 10, 2010
Jonathan M Davis
Sep 10, 2010
Bernard Helyer
Sep 10, 2010
Cavalary
Sep 10, 2010
bearophile
Sep 11, 2010
Jonathan M Davis
Sep 11, 2010
bearophile
Sep 11, 2010
Jonathan M Davis
Sep 11, 2010
Cavalary
Sep 12, 2010
Jonathan M Davis
Sep 12, 2010
Cavalary
Sep 12, 2010
Jonathan M Davis
Sep 14, 2010
Ali Çehreli
Sep 12, 2010
bearophile
[OT] Re: Input handling? (newbie alert!)
Sep 14, 2010
Ali Çehreli
Sep 14, 2010
Jonathan M Davis
September 09, 2010
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...
September 10, 2010
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!
September 10, 2010
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
September 10, 2010
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! >_<;
September 10, 2010
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 :)
September 10, 2010
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
September 11, 2010
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
September 11, 2010
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
September 11, 2010
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
September 11, 2010
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...
« First   ‹ Prev
1 2