在我建立一个包含学生信息的文本文件,并向文件输出数据时,出现了堆栈问题。源码如下:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//学生信息
char name[30];
int number,score;
char fileName[30];
cout<<"Please input the name of student file:\n";
cin>>fileName; //输入文件名
ofstream outstuf(fileName,ios::out); //关联文件和流
if(!outstuf) //成功打开文件检测
{
cerr<<"File could not be open."<<endl;
abort();
}
outstuf<<"学生成绩文件\n";
cout<<"Input the number,name,and score:"
<<"(Enter Ctrl+Z to end input)\n? ";
while(cin>>number>>name>>score)
{
//向文件顺序写入学生信息
outstuf<<number<<' '<<name<<' '<<score<<'\n';
cout<<"? ";
}
outstuf.close();
return 0;
}
结果
Please input the name of student file:
D:\\ApplicationWorkSpace\\C++\\ReadandWriteStuScore\\student.txt
Input the number,name,and score:(Enter Ctrl+Z to end input)
? 20200301 阿花 89
? 20200302 阿牛 92
? 20200309 二狗 66
? ^Z
请按任意键继续. . .
文件内容能够成功插入:
报错如下:
错误提示,name附近出现堆栈的问题,这种情况下一般就是出现数组越界的情况。
解决方式:
仔细查看发现,声明的 fileName[] 数组,容量为30。我们却对其赋值为 “D:\\ApplicationWorkSpace\\C++\\ReadandWrite StuScore\\student.txt”,给与的字符串远远大于30,出现数组越界,导致了这个问题,将数组容量扩大后,问题消失。即:
char fileName[300];