首页 > 解决方案 > 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);
  }

标签: c++codeblocks

解决方案


这里有几个错误和假设可能会出错。我将只关注立即显而易见的。

#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。


推荐阅读