从txt文件中读取文本行 [英] reading text lines from a txt file

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

问题描述

嗨大家好

我试图逐行读取txt文件中的一些文本,例如在控制台窗口中打印,所以我写下这些代码:



 命名空间 test1 
{
class 程序
{
静态 void Main( string [] args)
{

StreamReader A;
A = new StreamReader( a。 TXT);
string line = A.ReadLine();
while (line!= null
{
Console。的WriteLine(线);
}
Console.ReadKey();

}
}
}





我的txt文件包含3行文字:1-阿里去学校2-水热3-我累了

所以当运行程序控制台窗口出现并打印第一行文字重复而且不要停止,直到我关闭那个。

我有两个问题:第一个为什么这个程序只读取我的文本的第1行并且不读其他行,第二个为什么这不会停止打印





谢谢大家

解决方案

使用正确的功能而不是重新发明轮子:见 File.ReadAllLines(...) [ ^ ]。

Andi



PS:在你的例子中,你没有读过循环中的下一行。


< blockquote>如果我是我会尝试:



  string  line; 
while ((line = A.ReadLine())!= null
{
Console.WriteLine(line);
}





你的问题是你在while块中创建一个无限循环;如果你想在某个时候有机会逃脱它,你必须在循环内修改你的行变量。



希望这会有所帮助。


您的代码应该是

 命名空间 test1 
{
class 计划
{
静态 void Main( string [] args)
{

StreamReader A;
A = new StreamReader( A. TXT);

while (!A.EndOfStream)
{
Console.WriteLine(A.ReadLine());
}
Console.ReadKey();

}
}
}


Hi Guys
I am trying to read some texts from txt file line by line and for example print it in console window, so I write these codes :

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            StreamReader A;
            A = new StreamReader("a.txt");
            string line = A.ReadLine();
            while (line!=null)
            {
                Console.WriteLine(line);
            }
            Console.ReadKey();
            
        }
    }
}



my txt file contains 3 line of text : 1- ali goes to school 2- water is hot 3- I am tired
so when run the program console windows show up and print the first line of text repetitive and don''t stop until I close that.
I have two problem: first why this program reads only line1 of my text and don''t read other lines, second why this won''t stop printing


thanks everyone

解决方案

Use the proper function instead of re-inventing the wheel: see File.ReadAllLines(...)[^].
Andi

PS: In your example, you don''t read the next line inside the loop.


If I were you, I would try :

string line;
while ((line = A.ReadLine()) != null)
{
   Console.WriteLine(line);
}



Your problem is you create an infinite loop in your while block ; you have to modify your line variable inside the loop if you want a chance to escape it sometime.

Hope this helps.


Your code should be

namespace test1
{
    class Program
    {
        static void Main(string[] args)
        {
            
           StreamReader A;
            A = new StreamReader("A.txt");           
            
            while (!A.EndOfStream)
            {
                Console.WriteLine(A.ReadLine());
            }
            Console.ReadKey();
            
        }
    }
}


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

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