On Friday, 11 January 2013 at 12:17:32 UTC, evilrat wrote:
On Friday, 11 January 2013 at 09:44:31 UTC, Lubos Pintes wrote:
Hi,
Do I correctly suppose this is not possible? Because I don't understand fully the compiler error.

import std.stdio;
void main() {
 int[] a;
 stdin.readf(" %s",&a);
 writeln(a);
}

what is the definition of format of "array" to read from file?

from your example it is reading formatted(%s = simply any string terminated by enter, also prepended by a space?) from standard input.

try something like this

import std.file, std.ascii;

void read()
{
// reads whole file to string, use std.file.byLine or others on large files
auto data = cast(string) read("path_to_file");

// array storing your data
int[] numbers;

// run through the all content readed from file
foreach(ch; data)
{
// if character is a number put it to numbers array
if ( std.ascii.isNumber(ch) )
  numbers ~= cast(int) ch;
}

}

Brrr....

Don't parse data yourself! Your code, for example, will only parse digits single digits, and will parse "25" as [2, 5]...

Use conv.to !

If your input is an actual array format, you can simply do this:

//----
import std.stdio;
import std.conv;
import std.string;

void main()
{
    auto file = File("data.txt", "r");
    foreach (line; file.byLine())
    {
        auto numbers = to!(int[])(line.strip());
        writeln(numbers);
    }
}
//----

Here is another approach, that will split your input into strings that only contains digits, and as such, can be parsed:
//----
import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.ascii;

void main()
{
    auto app = appender!(int[])();
    auto file = File("data.txt", "r");
    foreach (line; file.byLine())
    {
auto stringEntries = std.algorithm.splitter!"!std.ascii.isDigit(a)"(line); auto numberEntries = stringEntries.filter!"!a.empty"().map!"to!int(a)"();
        app.put(numberEntries);
    }
    writeln(app.data);
}
//----
Even this approach is kind of hackish though, and will not support numbers in hex format for example, or floats either. But that's the best you get for a completely generic parser that has no information on format what so ever.

Reply via email to