c++ - C++ 程序报告“进程终止,状态为 -1073741510”
问题描述
我正在用 C++ 做一个算法和数据结构练习,它需要读取一个十字的 txt 文件,然后使用没有 STL、类或结构的堆栈以保留的顺序显示它们。所有代码看起来都不错,但是当我实际运行它时它什么也没显示。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int mindex = -1;
string word[10];
void push(string p);
void top();
void pop();
bool isEmpty();
int main()
{
string filename,eli;
cout << "Please input a file name" << endl;
cin>>filename;
ifstream inData;
inData>>eli;
inData.open(filename);
if (!inData)
{
cerr<< "Error opening : " << filename << endl;
return -1;
};
while (inData >> eli)
{
if(inData.fail()){
break; }
else push(eli);
}
while (!isEmpty()){
top();
pop();
}
inData.close();
return 0;
}
void push(string p){
index++;
word[mindex] = p;
}
void pop(){
mindex--;
}
void top(){
cout<<word[mindex]<<" ";
}
bool isEmpty(){
return (mindex<0);
}
解决方案
这里有几个错误和假设可能会出错。我将只关注立即显而易见的。
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // only for demos/slideware/toy projects.
int mindex = -1;
string word[10]; // we will only ever get 10 strings?
// 10 is a magic number use a const like const int maxWords = 10;
// using std::array will catch problems like this, std::vector can be used to dynamically resize the array.
void push(string p);
void top();
void pop();
bool isEmpty();
int main() {
string filename,eli;
cout << "Please input a file name" << endl;
cin>>filename;
ifstream inData;
inData>>eli; // reading from not open file!!!
inData.open(filename);
if (!inData) {
cerr<< "Error opening : " << filename << endl;
return -1;
};
while (inData >> eli) {
if(inData.fail()) {
break;
} else
push(eli);
}
while (!isEmpty()){
top();
pop();
}
inData.close();
return 0;
}
void push(string p){
index++; // did you mean mindex???
word[mindex] = p; // fatal error if mindex is not at least 0.
}
void pop(){
mindex--;
}
void top(){
cout<<word[mindex]<<" ";
}
bool isEmpty(){
return (mindex<0);
}
除非您绝对确定永远不会超过 10 个单词,否则应在某处检查 mindex 是否超过 10。
推荐阅读
- forms - 在表单提交之前执行异步功能
- android - android studio - 在调试模式下从已安装的应用程序中取出样式
- sql - 在 Power Bi 中将 SQL 查询转换为 DAX 以从表中获取单个值
- math - 傅里叶逆变换虚部数的物理意义是什么?
- python - sympy.plotting.plot3d 不绘制常量函数
- python - 动态访问文本文件中的特定标签并获取其下的元素并再次从下一个单词开始并使用python获取其下的元素
- javascript - 带有 base64 嵌入字体的序列化 SVG 图像,在 IE Edge 中无法正确呈现
- rdf - 关于属性特征的问题
- vmware - 无法下载最新的 VimService.dll 文件
- docker - 如何正确共享一个 jupyter docker 来托管