Input handling? (newbie alert!)

Cavalary cavalary1684 at hotmail.com
Thu Sep 9 09:20:19 PDT 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...


More information about the Digitalmars-d-learn mailing list