C++计划报告"Process terminated with status -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);
}

除非你绝对确定mindex的单词永远不会超过10个,否则应该在某个地方检查mindex是否在10个以上。

相关内容

最新更新