首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >读文件和写文件

读文件和写文件
EN

Stack Overflow用户
提问于 2019-05-30 18:41:34
回答 1查看 462关注 0票数 0

似乎无法将我的数据作为整数读取并打印出来。另外,在def read (文件)函数中有一个count = aFile.gets的关闭流(IOError)。这个程序包括数组,文件和循环。这个程序的目的是获取一个数字10,并将这个数字写到一个文件中,然后在传递的每一行中,从0递增到10。

# takes a number and writes that number to a file then on each line
# increments from zero to the number passed
def write(aFile, number)
  # You might need to fix this next line:
  aFile.puts("number")
  index = 0
  while (index < number)
   aFile.puts(number.to_s)
   index += 1
  end
end

# Read the data from the file and print out each line
def read(aFile)

  # Defensive programming:
  count = aFile.gets
  if (is_numeric(count))
    count = count.to_i
  else
    count = 0
    puts "Error: first line of file is not a number"
  end

  index = 0
  while (count < index)
    line = aFile.gets
    puts "Line read: " + line
  end
end

# Write data to a file then read it in and print it out
def main
  aFile = File.new("mydata.txt", "w") # open for writing
  if aFile  # if nil this test will be false
    write(aFile, 10)
  else
    puts "Unable to open file to write!"
  end

  if aFile
    read(aFile)
  end
  aFile.close
end

# returns true if a string contains only digits
def is_numeric?(obj)
  if /[^0-9]/.match(obj) == nil
    true
  end
  false
end

main
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-30 23:43:28

如果您想让您的代码正常工作,请更改:

aFile = File.new("mydata.txt", "w")

至:

aFile = File.new("mydata.txt", "r+")

您可以更改:

 count = aFile.gets
 if (is_numeric(count))

至:

  count = aFile.gets.to_i
 if (count.is_a?(Fixnum))

然后摆脱is_numeric?(obj)方法。

此外,您没有递增计数器,您也可以修复它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56376662

复制
相关文章

相似问题

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