[英]How to read character by character in text file line using C#
I'm new to C#, so sorry if you find my question stupid.我是 C# 的新手,如果你觉得我的问题很愚蠢,很抱歉。
What I need to do is read a line in text file and show the in我需要做的是读取文本文件中的一行并显示
Console.WriteLine().
So far, I tried this code, but it did nothing but show the counting of characters...到目前为止,我尝试了这段代码,但它除了显示字符计数外什么也没做……
What I'm looking for is to show each character, then step forward to the next, and so forth....我正在寻找的是显示每个角色,然后前进到下一个,依此类推......
Here is my code:这是我的代码:
if (File.Exists(path))
{
StreamReader MyStreamReader = new StreamReader(path);
for (int i = 0; i < 99; i++)
{
int char = MyStreamReader.Read();
Console.WriteLine(char);
Console.ReadLine();
}
MyStreamReader.Close();
}
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.Write((char)sr.Read());
}
}
I don't exactly know what you're trying to do, but a definite mistake of yours is that your interpreting the characters you read as integers, while you want them as chars.我不完全知道你想做什么,但你的一个明显错误是你将你读的字符解释为整数,而你想要它们作为字符。 So you should exchange
所以你应该换
int char = MyStreamReader.Read();
with和
char c = (char) MyStreamReader.Read();
And use c
instead of char
in the following line:并在以下行中使用
c
而不是char
:
Console.WriteLine(c);
If you need further help, please clarify your question.如果您需要进一步的帮助,请澄清您的问题。
char Ch = (char)MyStreamReader.Read();
Console.WriteLine(rc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.