读取文件流并转换为字符数组时出错

Visual C++ Error Reading Filestream and Converting to Array of Characters

本文关键字:字符 数组 出错 转换 文件 读取      更新时间:2023-10-16

首先这里是我试图得到工作的代码-

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循环行。任何帮助都是感激的!

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