Visual C ++错误读取文件流并转换为字符数组

时间:2011-12-29 17:33:28

标签: c++ winforms visual-studio-2010 visual-c++ c++-cli

首先,这是我试图开始工作的代码 -

private: System::Void openToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {
         OpenFileDialog^ dlg = gcnew OpenFileDialog();
         dlg->Filter = "Text Files|*.txt";
         String^ stream;
         if(dlg->ShowDialog()==Windows::Forms::DialogResult::OK)
         {
            txtOutput->Text = System::IO::File::ReadAllText(dlg->FileName);


            char* num = (char*)(void*)Marshal::StringToHGlobalAnsi(stream); //Convert string to array of char

            for (int i=0;i<stream->Length;++i) //ERRONEOUS LINE!!
            {
                num[i] = num[i] ^ key;   //DECRYPT
            }
            String^ orig_stream = gcnew String(num);
            txtOutput->Text = orig_stream;

         }
     }

我正在尝试打开已加密的文件。该程序编译没有任何错误,但在运行时它给我以下错误与断开,继续或中止的选项:

An unhandled exception of type 'System.NullReferenceException' occurred in Project_Targaryen.exe
Additional information: Object reference not set to an instance of an object.

错误指向for循环线。 任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

stream在for循环中使用之前与对象无关。