Created
April 12, 2009 16:23
-
-
Save snuxoll/94051 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
to compile: | |
valac -o sum --pkg vala-1.0 stdin_reader.vala sum_application.vala |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using GLib; | |
namespace snuxoll { | |
class StdinReader : Gee.Iterable<string>, | |
Gee.CollectionObject<string> { | |
public StdinReader () { | |
} | |
public bool eof() { | |
return stdin.eof(); | |
} | |
public Type get_element_type() { | |
return typeof(string); | |
} | |
public Gee.Iterator<string> iterator() { | |
return new Iterator<string>(this); | |
} | |
public string? read_line() { | |
var line = new StringBuilder(); | |
var buffer = new char[1024]; | |
while ( ( !line.str.has_suffix ("\n") ) ) { | |
string chunk = stdin.gets(buffer); | |
if (chunk != null) { | |
line.append(chunk); | |
} else { | |
return null; | |
} | |
} | |
return line.str; | |
} | |
private class Iterator<T> : Gee.Iterator<T>, | |
Gee.CollectionObject<T> { | |
private StdinReader reader { get; set; } | |
public Iterator(StdinReader _reader) { | |
reader = _reader; | |
} | |
public bool next() { | |
return reader.eof(); | |
} | |
public T? get() { | |
return reader.read_line(); | |
} | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using GLib; | |
using snuxoll; | |
class SumApplication : Object { | |
private uint64 total { get; set; } | |
public SumApplication() { | |
this.total = 0; | |
} | |
public void run() { | |
var reader = new StdinReader(); | |
foreach(string line in reader) { | |
var nums = line.strip().split(" "); | |
foreach(string num in nums) { | |
this.total += num.to_int(); | |
} | |
} | |
stdout.printf("Grand Total: %llu\n", total); | |
} | |
static int main(string[] args) { | |
var app = new SumApplication(); | |
app.run(); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment