【发布时间】:2015-10-24 09:59:18
【问题描述】:
我有一个链表,它接受多个输入文件,然后将它们放入链表中以便稍后打印。
我实现了一个打印功能,但它不能很好地工作并给出访问冲突错误。我尝试调试,不幸的是我找不到问题的根源。
函数中的错误行:
cout << ptr2->command + " ";
运行时错误:
file.exe 中 0x00DAC616 处的第一次机会异常:0xC0000005:访问冲突读取位置 0xCDCCDCDE1。
代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include "strutils.h"
using namespace std;
struct Commands;
struct Functions
{
string fname;
Functions *right;
Commands *down;
};
struct Commands
{
string command;
Commands *next;
};
Functions *head;
Functions *temp;
Commands *temp2;
void StreamToLinkedList(ifstream &inputfile)
{
string s;
getline(inputfile, s);
temp = new Functions();
temp->fname = s.substr(0, s.length());
temp2 = temp->down;
while (!inputfile.eof())
{
getline(inputfile, s);
temp2 = new Commands();
temp2->command = s.substr(0, s.length()-1) + ",";
temp2 = temp2->next;
}
inputfile.clear();
inputfile.seekg(0);
}
void printLinkedList()
{
Functions *ptr = head;
Commands *ptr2;
while (ptr != nullptr)
{
cout << ptr->fname << endl;
ptr2 = ptr->down;
while (ptr2 != nullptr)
{
cout << ptr2->command + " ";
ptr2 = ptr2->next;
}
cout << endl;
ptr = ptr->right;
}
}
int main()
{
string file, key, s;
ifstream input;
cout <<"If you want to open a service (function) defining the file," << endl
<<"then press (Y/y) for 'yes', otherwise press any single key" << endl;
cin >> key;
ToLower(key);
if (key == "y")
{
cout << "Enter file the input file name: ";
cin >> file;
input.open(file.c_str());
if (input.fail())
{
cout << "Cannot open the file." << endl
<< "Program terminated." << endl;
cin.get();
cin.ignore();
return 0;
}
else
{
StreamToLinkedList(input);
head = temp;
temp = temp->right;
}
}
else
{
cout << "Cannot found any input file to process" <<endl
<< "Program terminated."<< endl;
cin.get();
cin.ignore();
return 0;
}
do
{
cout<< "Do you want to open another service defining file?"<<endl
<< "Press (Y/y) for 'yes', otherwise press any key" <<endl;
cin >> key;
ToLower(key);
if (key == "y")
{
cout << "Enter file the input file name: ";
cin >> file;
input.open(file.c_str());
if (input.fail())
{
cout << "Cannot open the file." << endl
<< "Program terminated." << endl;
cin.get();
cin.ignore();
return 0;
}
else
{
StreamToLinkedList(input);
temp = temp->right;
}
}
} while ( key == "y");
cout << "-------------------------------------------------------------------" << endl
<< "PRINTING AVAILABLE SERVICES (FUNCTIONS) TO BE CHOSEN FROM THE USERS" << endl
<< "-------------------------------------------------------------------" << endl << endl;
printLinkedList();
cin.get();
cin.ignore();
return 0;
}
错误代码可能是什么?
【问题讨论】:
-
你忘了问问题。您尝试调试什么?
-
真的要实现自己的链表吗? vs std::list
-
对于第一个问题,我调试了它,因为我必须确保它确实有效;第二,我必须实现我自己的链表。
-
0xCDCDCD ... 是 Microsoft VC 调试版本填充未初始化数据的典型。这是扩展,在正常的“非调试”C++ 中,此类区域将具有随机值。
-
我应该将这些指针初始化为 nullptr 吗?
标签: c++ linked-list