C# 如何从文件中读取一行?
我试图读一整行,但ReadLine是string,我从文件中提取的第一个内容是:123456 123456 十五 2011年 69.99 书 用C解决问题++ 沃尔特·萨维奇 (实际文本文件之间没有空行)C# 如何从文件中读取一行?,c#,C#,我试图读一整行,但ReadLine是string,我从文件中提取的第一个内容是:123456 123456 十五 2011年 69.99 书 用C解决问题++ 沃尔特·萨维奇 (实际文本文件之间没有空行) 然后是15然后是2011,我应该用哪一个?阅读我是否需要使用某种循环来计算行尾是什么时候?您需要使用类似int.parse的函数将字符串解析为一个数字。如果您在记事本中打开文件,您可能会发现在其他文本编辑器中看不到行空格 ReadinLine()应一直读取,直到找到字符“\n” 对不起,如果你
然后是15然后是2011,我应该用哪一个?阅读我是否需要使用某种循环来计算行尾是什么时候?您需要使用类似
int.parse的函数将字符串解析为一个数字。如果您在记事本中打开文件,您可能会发现在其他文本编辑器中看不到行空格
ReadinLine()应一直读取,直到找到字符“\n”
对不起,如果你已经知道这一点,但它让我疯狂了一段时间,直到我最终发现有行空间我看不见。试试记事本,试试写字板,。。您看到任何差异了吗?对于int值,您仍然必须使用ReadLine(),但必须将其解析为int
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace as2
{
class Program
{
static void Main(string[] args)
{
int id = 0, stock = 0, published = 0, newstock = 0;
double price = 0.00;
string type = " ", title = " ", author = " ";
Program inventroy = new Program();
inventroy.read_one_record(ref id, ref stock, ref published, ref price, ref type, ref title, ref author);
Console.WriteLine("Update Number In Stock");
Console.WriteLine("=======================");
Console.Write("Item ID: ");
Console.WriteLine(id);
Console.WriteLine("Item Type: ");
Console.Write(type);
}
void read_one_record(ref int id, ref int stock, ref int published, ref double price, ref string type, ref string title, ref string author)
{
StreamReader myFile = File.OpenText("Inventory.dat");
id = int.Parse(myFile.ReadLine());
stock = int.Parse(myFile.ReadLine());
published= int.Parse(myFile.ReadLine());
stock = int.Parse(myFile.ReadLine());
price = double.Parse(myFile.ReadLine());
type = myFile.ReadLine();
title = myFile.ReadLine();
author = myFile.ReadLine();
myFile.Close();
}
void write_one_record(int id, int newstock, int published, double price, string type, string title, string author)
{
StreamWriter myFile = new StreamWriter(File.OpenWrite("Inventory.dat"));
myFile.WriteLine(id);
myFile.WriteLine(newstock);
myFile.WriteLine(published);
myFile.WriteLine(price);
myFile.WriteLine(type);
myFile.WriteLine(title);
myFile.WriteLine(author);
myFile.Close();
}
}
}
嗯?ReadLine()
有什么问题吗?我试图将123456保存为int。意思是ReadLine保存为字符串。无法将类型字符串保存为int类型。所以您的问题不是如何读取行,而是如何将字符串转换为数字或如何从文件中读取数字。请重新表述你的问题。@Nogg:我不知道你刚才问了什么。瓦什说得很对;你的问题很容易让人误解。谢谢,这很有效,但当我执行代码时,我会出错。有什么帮助吗?我将更新代码。未处理的异常:System.FormatException:输入字符串的格式不正确,这意味着该字符串不是有效的数字。
void read_one_record(ref int id, ref int stock, ref int published, ref double price, ref string type, ref string title, ref string author)
{
StreamReader myFile = File.OpenText("Inventory.dat");
id = int.Parse(myFile.ReadLine());
stock = int.Parse(myFile.ReadLine());
published= int.Parse(myFile.ReadLine());
stock = int.Parse(myFile.ReadLine());
price = double.Parse(myFile.ReadLine());
type = myFile.ReadLine();
title = myFile.ReadLine();
author = myFile.ReadLine();
myFile.Close();
}