Bodokh
Bodokh

Reputation: 1066

read one char at a time until i reach an empty space in C#

I'm really lost here, don't know what i did wrong.

StreamReader reader = new StreamReader (@"Destination.txt");
int i=0;
char[] word = new char[16];
While (reader.Peek().ToString() != " ")
{
    word[i] = (char)reader.Read(); //This is when the debugger stops, after 16 iterations.
    i++;
}

I know that for sure, that in the txt, there is always a space after a maximum of 15 characters so it shouldn't exceed the word array boundary, but it does. What am i doing wrong here? The reason i used Tostring is because it the Peek command kept returning an Int for some reason.

Upvotes: 1

Views: 296

Answers (2)

f14shm4n
f14shm4n

Reputation: 461

When StreamReader.Peek() return -1 , that mean end of file.

while (reader.Peek() != -1)

Upvotes: 0

Andrei
Andrei

Reputation: 56688

Peek returns the code of the char, not the char itself, so you need to convert it:

while ((char)reader.Peek() != ' ')

Upvotes: 3

Related Questions