从文件到数组的数据 [英] Data from a file into an array

查看:69
本文介绍了从文件到数组的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我有一个名为grades.txt的文件,我需要从中输入数据(数字列表)并将这些数字添加到数组中,以便获得平均值.到目前为止,这就是我所拥有的,它当前从文件中获取数字并显示它们 但是我不确定如何将它们添加到数组中?

basically I have a file that is named grades.txt and I need to input the data from it (a list of numbers) and add those numbers to an array so I can get the average. so far this is what I have, it currently gets the numbers from the file and displays them but I'm not sure how to add them to an array?

 课程计划
    {
      静态void Main(string [] args)
       {
  class Program
    {
        static void Main(string[] args)
        {

推荐答案

使用TryParse将每一行转换为数字.

Use TryParse to convert each line to a number.

https://msdn.microsoft.com /en-us/library/system.int32.tryparse%28v=vs.110%29.aspx

接下来,设置一个变量以跟踪数组中元素的数量.将其初始化为零,并在每次读取一行时将其递增一.然后,使用该数字作为数组的索引.将该索引处的元素设置为您得到的数字 从TryParse返回.

Next, set a variable to keep track of how may elements there are in the array. Initialise it to zero, and increment it by one each time you read a line. Then, use that number as an index into the array. Set the element at that index to the number you get back from TryParse.

您还可以考虑使用List< int>而不是数组(除非您要处理专门告诉您使用数组的作业问题).

You might also consider using List<int> rather than an array (unless you are dealing with a homework question that specifically tells you to use an array).

https://msdn.microsoft.com/zh-CN /library/6sh2ey19%28v=vs.110%29.aspx


这篇关于从文件到数组的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆