Week 2: Notes

In Pascal we could read whitespace-separated integers like this:

var
  i: integer;
  sum: integer = 0;

begin
  while not seekEof do
    begin
      read(i);  // read a decimal integer, ignoring whitespace
      sum += i;
    end;
end;

In C# there is no built-in method to read integers in this way, so we have to do a bit more work.

Here is a C# method that will read the next integer from standard input, ignoring whitespace.

// Read an integer, ignoring whitespace.  Returns -1 on end of input.
static int readInt() {
  string s = "";

  while (true) {
    int i = Read();
    if (i == -1)
      return s == "" ? -1 : int.Parse(s);
      
    char c = (char) i;
    if (char.IsWhiteSpace(c)) {
      if (s != "")
        return int.Parse(s);
    } else s += c;
  }
}