簡體   English   中英

在C#中的一行中讀取不同的數據類型

[英]Reading different data types in a single line in C#

我有一個像這樣的文件格式:

14 00 1.5121
14 01 1.3922
14 02 1.2231

遵循以下結構

int int double

以空格分隔。

目前,我的代碼是:

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

但是我被困在如何使用buff自動解析int int double格式。 C#中有一個函數可以讓我做到這一點嗎?

謝謝!

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]);

C#中有一個函數可以讓我做到這一點嗎?

如果您逐行讀取文件並用空格將其分割,則可以。 您可以使用Int32.ParseDouble.Parse方法。

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

在此while語句中,您可以像下面那樣拆分和解析值;

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

請記住,如果您不提供任何IFormatProvider ,則此方法默認情況下使用CurrentCulture 如果您的CurrentCultureNumberDecimalSeparator不是. Double.Parse方法將引發FormatException

但我通常建議使用其TryParse方法而不是Parse方法,因為如果解析操作將失敗,則此TryParse方法將返回false而不是TryParse異常。

首先將每個輸入行拆分為字段:

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

然后分別解析每個字段:

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

根據文件的來源(內容的可靠性),您應該添加很多錯誤處理和防御性編程(使用TryParse())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM