Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 试图打开.txt文件时程序崩溃_C++_File Io_Linked List - Fatal编程技术网

C++ 试图打开.txt文件时程序崩溃

C++ 试图打开.txt文件时程序崩溃,c++,file-io,linked-list,C++,File Io,Linked List,当我试图运行我的程序时,它一开始就崩溃了。问题是我的输入来自文件,我可以很好地写入文件。有人能解释一下为什么这个代码不起作用吗 StringList::StringList() { pTop=NULL; pBottom=NULL; ifstream in; in.open("read.txt"); StringListNode * pCurrent; pCurrent = new StringListNode; pCurrent = pTop; while(

当我试图运行我的程序时,它一开始就崩溃了。问题是我的输入来自文件,我可以很好地写入文件。有人能解释一下为什么这个代码不起作用吗

StringList::StringList()
{
  pTop=NULL;
  pBottom=NULL;

  ifstream in;
  in.open("read.txt");

  StringListNode * pCurrent;
  pCurrent = new StringListNode;
  pCurrent = pTop;

  while(!in.eof())  //reads it till the end of file
  {
    in >> pCurrent->data;
    pCurrent = pCurrent->pNext;
  }
  in.close();
}
该文件的输出工作正常。我想我会把它包括进去

StringList::~StringList()
{
  ofstream out;
  out.open("read.txt");

  StringListNode * pCurrent;
  pCurrent = new StringListNode;
  pCurrent = pTop;
  while(pCurrent != 0)  
  {
    out << pCurrent->data << endl;
    pCurrent = pCurrent->pNext;
  }
  out.close();
 }
StringList::~StringList()
{
流出的液体;
out.open(“read.txt”);
StringListNode*pCurrent;
pCurrent=新的StringListNode;
pCurrent=pTop;
while(pCurrent!=0)
{
输出数据pNext;
}
out.close();
}

pCurrent=pTop为什么在此处分配此项?这使
pCurrent
指针为空。请移除或修复

我对您的代码感到困惑:

pCurrent = new StringListNode; // Allocate new memory and point at it
pCurrent = pTop; // Make pCurrent point at same thing as pTop
您分配给
pCurrent
两次
pTop
看起来像一个数据成员,也许您的意思是在构造函数中:

pCurrent = new StringListNode; // Allocate new memory and point at it
pCurrent->pNext = nullptr; // Assign null to next pointer
pTop = pCurrent; // Make pTop point at new memory
在析构函数中,remove
pccurrent=newStringListNode因为它什么都不做

输出时,检查
pCurrent!=0,但在读取时不检查null。可能
pCurrent
是空指针

另外,请阅读。您的循环应该是:

while(pCurrent && (in >> pCurrent->data)) 
{
   pCurrent = pCurrent->pNext;
}

太棒了,谢谢你修复了我的崩溃问题,但是它没有显示文件中的文本。请删除
pccurrent=pTop,你为什么要做这个作业?啊,那让我无比沮丧,它现在可以工作了。非常感谢。@GiBiT09:它读了整个文件吗?看起来它只从文件中读取一次。也许你需要通过在循环中分配新的内存来构建链表,但我会留给你去弄清楚。是的,它只显示文件中的第一个。因此,如果我在循环中创建一个指针,比如StringListNode*pNew;pNew=pNew->pNext;??