John Tan
John Tan

Reputation: 1385

Reading different data types in a single line in C#

I have a file format that goes like this:

14 00 1.5121
14 01 1.3922
14 02 1.2231

following a structure of

int int double

delimited by spaces.

Currently my code is:

StreamReader file = new StreamReader("file_to_open.txt");
String buff;
while( file.peek() > 0 )
{
    buff = file.ReadLine();
}

However I am stuck at how to use buff to parse the int int double format automatically. Is there a function in C# that allows me to do that?

Thanks!

Upvotes: 1

Views: 1293

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

Is there a function in C# that allows me to do that?

If you read your file line by line and split it with white space, yes there is. You can use Int32.Parse and Double.Parse methods.

string line;
StreamReader file = new StreamReader("file_to_open.txt");
while((line = file.ReadLine()) != null)
{
    //
}

And in this while statement, you can split and parse your values like;

var array = line.Split(null);
int firstInt = Int32.Parse(array[0]);
int firstInt = Int32.Parse(array[1]);
double firstDouble = Double.Parse(array[2]);

Remember, this method uses CurrentCulture by default if you don't provide then any IFormatProvider. If your CurrentCulture's NumberDecimalSeparator is not ., Double.Parse method throws FormatException.

But I generally suggest using their TryParse methods instead of Parse methods because if parsing operation will fail, this TryParse methods returns false instead of throwing exception.

Upvotes: 1

DrKoch
DrKoch

Reputation: 9772

First split each input line into fields:

string[] fields = buff.Split(' ');

then parse each field individually:

if(fields.Length < 3) throw...
int i1 = int.Parse(field[0];
int is = int.Parse(field[1];
string s = field[2];

Depending on the source of your file (how reliable is its contents) you should add a lot of error handling and defensive programming (use TryParse())

Upvotes: 1

chouaib
chouaib

Reputation: 2817

string line = file.ReadLine;
string[] elements = line.Split(' ');

int a = Convert.ToInt32(elements[0]);
int b = Convert.ToInt32(elements[1]);
double c = Convert.ToDouble(elements[2]);

Upvotes: 3

Related Questions