文件输出c++时程序崩溃
Program crash on file output c++
当我尝试将结果输出到.txt
文件时,我的程序意外崩溃。
基本上,我想将学生列表存储在.txt
文件中,并在以后方便地检索它们。我的程序可以将值存储为变量,但当你想将它们保存到输出文件时,程序本身就会崩溃。
这是我的代码
//STUDENTS CLASS
char** studentNames;
int numberOfNames;
void Students::setNumberOfNames(int namenumbers) // Takes in the number of student names to store
{
numberOfNames = namenumbers;
}
void Students::setStudentNames() // Takes a number of student names and stores them.
{
char studentinput[128]
studentNames = new char*[numberOfNames];
for (int i=0; i<=numberOfNames; i++)
{
studentNames[i] = new char[128];
cout << "Student " << i << ": " << "n";
cin.getline(studentinput, sizeof(studentinput));
strcpy(studentNames[i], studentinput);
}
}
//MAIN CLASS
Student s;
int nums;
int main()
{
cout << "How many names would you like to store? " << endl;
cin >> nums;
s.setNumberOfNames(nums):
s.setStudentNames();
for(int i=0; i<=s.numberOfNames; i++)
{
cout << s.numberOfNames [i] << "n"; // THIS WORKS FINE! DOES WHAT I SAY :)
}
// THIS IS WHERE IT CRASHES. I TRY AND STORE THE NAMES INTO THE `.txt` FILE.
//IF YOU WANT TO STORE 3 NAMES, IT WORKS FINE, BUT IF YOU WANT TO STORE LIKE
//12 NAMES THE WHOLE THING CRASHES. WHEN I COMMENT OUT THE BOTTOM BLOCK
//OF CODE THE PROGRAM WORKS FINE, BUT I WANT TO STORE THE NAMES.
ofstream outputFiles ("example.txt");
if(outputFiles.is_open())
{
for(int i=0; i<=s.numberOfNames; i++)
{
outputFiles << s.studentNames [i] << "n";
}
}
}
更改
for (int i=0; i<=numberOfNames; i++)
至
for (int i=0; i < numberOfNames; i++)
程序中的任何位置。
相关文章:
- 程序崩溃并显示"std::out_of_range"错误
- 试图创建流或fopen时程序崩溃
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 如何找出应用程序崩溃的原因 - Win 10 LTSB
- 操纵安卓相机的深度图导致应用程序崩溃
- 为什么当我尝试搜索双链表中第一个数据条目之外的数据时,程序崩溃了?
- DLL Made with CMake 使程序崩溃
- 程序崩溃使用boost::asio
- 调用 free() 有时会导致程序崩溃
- 邮件加密程序崩溃
- 调用 java 的回调() 时应用程序崩溃.由于 detatchThread 而获得运行时错误
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- For 循环在尝试读取数组 c++ 时程序崩溃
- 即使有 0 个错误,Getter 似乎也会使程序崩溃
- Windows桌面程序保存您的计算机会话 - 基于程序崩溃时的恢复会话
- 无法访问的代码如何导致我的程序崩溃?
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- QCompleter set模型使应用程序崩溃
- 使用唯一指针调用函数会使我的程序崩溃
- 删除SDL_PollEvent时程序崩溃