【发布时间】:2010-03-06 01:29:08
【问题描述】:
以下代码应该读取文件的每一行并对其进行操作。但是,它只读取第一行。如果没有 for 循环,它会读取整个文件。老实说,我不知道为什么它没有阅读全文。
StreamReader sr = new StreamReader(gridPath);
string line;
char[] lineCh;
char current;
int x, y;
bool north, east, south, west;
x = y = 0;
while ((line = sr.ReadLine()) != null)
{
lineCh = line.ToCharArray();
for (int i = 0; i < lineCh.Length; i++)
{
current = lineCh[i];
north = CheckInput(current);
current = lineCh[++i];
east = CheckInput(current);
current = lineCh[++i];
south = CheckInput(current);
current = lineCh[++i];
west = CheckInput(current);
i++; // Hop over space
grid[x, y] = new GridSquare(north, east, south, west);
x++; // Start next column
}
Console.WriteLine(line);
y++;
}
如果没有 for 循环,以下工作并打印整个文件:
StreamReader sr = new StreamReader(gridPath);
string line;
char[] lineCh;
char current;
int x, y;
bool north, east, south, west;
x = y = 0;
while ((line = sr.ReadLine()) != null)
{
lineCh = line.ToCharArray();
Console.WriteLine(line);
y++;
}
sr.Close();
CheckInput如下:
private bool CheckInput(char c)
{
switch (c)
{
case 'y':
return true;
case 'n':
return false;
default:
return true;
}
}
一个示例输入文件:
nyyn nyyy nyyy nyyy nyyy nnyy
yyyn yyyy yyyy yyyy yyyy ynny
yyyn yyyy yyyy yyyy ynyy nnnn
yyyn yyyy yyyy yyyy ynyy nnnn
yyyn yyyy yyyy yyyy yyyy nnyy
yynn yyny yyny yyny yyny ynny
【问题讨论】:
-
顺便说一句,你不需要把字符串转成字符数组,String上面直接有索引器就可以用了
-
可能是因为文件包含一行?
-
@tsv:你能告诉我们读取整个文件的代码吗?
CheckInput函数到底是什么?您是否在调用堆栈上方的某处捕获异常? -
@tsv:假设 Visual Studio:转到 Debug -> Exceptions,在 Common Language Runtime Exceptions 旁边,单击 Throw 下的复选框。单击确定,然后在调试器中运行您的代码。
-
与问题无关,但您应该使用带有
StreamReader的 using 语句以确保其正确处理
标签: c# streamreader