首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中从文本文件中读取数字

在C#中从文本文件中读取数字
EN

Stack Overflow用户
提问于 2009-12-28 15:11:36
回答 6查看 77.6K关注 0票数 23

这应该是非常简单的事情。我只想从一个由空格分隔的标记组成的文本文件中读取数字和单词。在C#中如何做到这一点?例如,在C++中,下面的代码可以读取整数、浮点数和单词。我不想使用正则表达式或编写任何特殊的解析代码。

ifstream in("file.txt");
int int_val;
float float_val;
string string_val;
in >> int_val >> float_val >> string_val;
in.close();

此外,每当读取令牌时,不应读入该令牌之外的一个字符。这允许进一步的文件读取取决于所读取的令牌的值。作为一个具体的示例,请考虑

string decider;
int size;
string name;

in >> decider;
if (decider == "name")
    in >> name;
else if (decider == "size")
    in >> size;
else if (!decider.empty() && decider[0] == '#')
    read_remainder_of_line(in);

解析一个二进制PNM文件也是一个很好的例子,说明了为什么您希望在读入一个完整的令牌后立即停止读取文件。

EN

回答 6

Stack Overflow用户

发布于 2009-12-28 15:20:50

using (FileStream fs = File.OpenRead("file.txt"))
{
    BinaryReader reader = new BinaryReader(fs);

    int intVal = reader.ReadInt32();
    float floatVal = reader.ReadSingle();
    string stringVal = reader.ReadString();
}
票数 10
EN

Stack Overflow用户

发布于 2009-12-28 16:20:01

这不完全是您问题的答案,但如果您是C#新手,则需要考虑的一个想法是:如果您使用自定义文本文件来读取一些配置参数,则可能需要检查.NET中的序列化主题。

XML序列化提供了一种写入和读取XML格式文件的简单方法。例如,如果您有一个配置类,如下所示:

public class Configuration
{
   public int intVal { get; set; }
   public float floatVal { get; set; }
   public string stringVal { get; set; }
}

您可以简单地使用XmlSerializer类保存并加载它:

public void Save(Configuration config, string fileName)
{
   XmlSerializer xml = new XmlSerializer(typeof(Configuration));
   using (StreamWriter sw = new StreamWriter(fileName))
   {
       xml.Serialize(sw, config);
   }
}

public Configuration Load(string fileName)
{
   XmlSerializer xml = new XmlSerializer(typeof(Configuration));
   using (StreamReader sr = new StreamReader(fileName))
   {
       return (Configuration)xml.Deserialize(sr);
   }
}

上面定义的Save方法将创建一个包含以下内容的文件:

<Configuration>
    <intVal>0</intVal>
    <floatVal>0.0</floatVal>
    <stringVal></stringVal>
</Configuration>

这种方法的好处是,如果Configuration类发生更改,则不需要更改SaveLoad方法。

票数 4
EN

Stack Overflow用户

发布于 2009-12-29 00:15:00

我喜欢使用StreamReader快速方便地访问文件。就像..。

  String file = "data_file.txt";    
  StreamReader dataStream = new StreamReader(file);   
  string datasample;
  while ((datasample = dataStream.ReadLine()) != null)
  {

     // datasample has the current line of text - write it to the console.
     Console.Writeline(datasample);
  }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1968328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档