gpt4 book ai didi

c++ - 文件输出时程序崩溃 C++

转载 作者:行者123 更新时间:2023-11-28 06:35:35 25 4
gpt4 key购买 nike

当我尝试将结果输出到 .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++)

程序中的任何地方。

关于c++ - 文件输出时程序崩溃 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26832754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com