Search code examples
c++-clistreamreader

Unable to get the end of file using StreamReader


I'm getting the next error using this code: (System.IndexOutOfRangeException)

int main(array<System::String ^> ^args)
{

String^ str="C:\\somefile.txt";

StreamReader^ sr=gcnew StreamReader(str);

String^ mystr=sr->ReadToEnd();

int i=0;

while (mystr[i++]!='\0')  //what's wrong wth this check?
{
  Console::Write(mystr[i]);
}
}

Solution

  • Nothing says that the string in a String class has to be zero-terminated like an old C-style string. Instead you should be getting the length from the string object itself.