reading numbers with C# from file

Started by
3 comments, last by Sneftel 17 years ago
hi,I have something like this in ASCII file : [double,double,double],int,[double,double,double],int, and so n times. In C I can use the fscanf with %f,%d arguments,but dont know what to do here. I can write my own funcktion to convert from text,but i dont think it will be fast.
Advertisement
I don't thing C# has the equivalent of fscanf. fscanf is not exactly type safe. Have you thought about using XML? C# has a lot of inbuilt support for XML. And you can make it type safe.

First up, create an XML schema (a .xsd file). This describes the content of the XML and the types for each field. Dev Studio has a GUI schema designer. Next, create the XML file based on the schema. Again, Dev Studio has a good interface for doing this.

To load the data:
DataSet data = new DataSet;data.ReadXmlSchema ("schema");data.ReadXml ("data");

The dataset now holds all the data in the XML, throwing an exception if there's an error somewhere.

The DataSet object is a simple database - it contains tables, rows and columns:
DataTable table = data.Tables ["tablename"];// iterates aver all rows in tableforeach (DataRow row in table.Rows){  // get a value from the row  value = (type) row ["columnname"];}

There is also a WriteXml function to allow you to save the data back to disk.

You can also perform database operations like filtering and sorting. This requires the use of the DataView type.

Skizz
Thanks for the reply.
Never tried xml, but as it is like that, I may give it a try.
Bear in mind that storing values in such a manner is not locale safe; that is, attempting to parse "1.463" as a double under a French locale will not work.

Probably the easiest workaround is to temporarily set your thread to the invariant culture when reading or writing to such files.

If your files are simple comma- or space-delimited lines of numbers, I'd just use ReadLine(), String.Split() and Double.TryParse().

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

Moved to For Beginners.

This topic is closed to new replies.

Advertisement