从文本文件中读取时C ++程序崩溃了吗?

时间:2015-03-03 03:50:27

标签: c++ shared-ptr

我正在制作一个程序,它从文本文件中读取一串数字,然后使用这些数字创建一个多项式。我正在使用链表创建多项式。列表中的每个节点表示多项式中的项。节点具有数据成员,例如系数和指数,显然是指向下一个节点(term)的指针。我不知道我的代码有什么问题,但是当我尝试从文本文件中读取时,我的程序崩溃了。我知道我的程序可以找到该文件(它位于同一个项目目录中),但只要输入名称并按Enter键就会停止运行。这是我的代码。

#include "polynomial.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>       // for exit() call

using namespace std;


void makePolynomials( shared_ptr<Polynomial> [], int *x );


int main()
   {
   shared_ptr<Polynomial> poly[ 100 ];
   int nPolynomials;

   makePolynomials( poly, &nPolynomials );

   // print out the polynomials
   // -------------------------
   for (int j=0; j < nPolynomials; j++)
      cout << *(poly[j]);

   return 0;
   }



void makePolynomials( shared_ptr<Polynomial> poly[], int *nPolynomials )
   {
   // get the filename from the user and open the file
   // ------------------------------------------------
   char filename[50];
   cout << "Enter the filename: ";
   cin >> filename;

   ifstream infile;
   infile.open( filename );
   if (! infile.is_open()) {
      cerr << "ERROR: could not open file " << filename << endl;
      exit(1);
      }

   // read in the data and construct a polynomial for each input line
   // ---------------------------------------------------------------
   string polynom;
   while (getline( infile, polynom ))
      {
      poly[ *nPolynomials ] = shared_ptr<Polynomial>(new Polynomial( polynom ));
      nPolynomials++;
      }
   }

类多项式构造函数

    Polynomial::Polynomial( string & str )
   {
   stringstream ss( str );  // stringstream lets us extract items separated by
                            // whitespace simply by using the >> operator
   double coefficient;      // to hold the coefficient
   int exp;                 // to hold the exponent
   head = nullptr;          // initialize head to null

   // read in coefficient-exponent pairs and add each term to the list
   // ----------------------------------------------------------------
   while (ss >> coefficient >> exp)
      if (coefficient != 0)   // don't make a 0 term
         head = shared_ptr<Term>(new Term( coefficient, exp, head ));
   }

1 个答案:

答案 0 :(得分:2)

可能以下行导致了问题:

   int nPolynomials; //contains a garbage value

成功:

  int nPolynomials=0; // or initialise it to any other value