提问者:小点点

进程已终止,状态为-1073741510需要来自king的帮助


我正在用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);
  }

共1个答案

匿名用户

这里有几个错误和假设可能出错。 我只会把注意力集中在那些立即显而易见的东西上。

#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应该在某处做,除非你绝对肯定永远不会有超过10个单词。