我有一個鏈接列表,它需要幾個輸入文件,然後將它們放入鏈接列表中以便稍後打印它們。打印鏈接列表 - 訪問衝突C++
我實現了一個打印功能,但它不能正常工作,並導致訪問衝突錯誤。我試圖調試,不幸的是我找不到問題的根源。
錯誤行的功能:
cout << ptr2->command + " ";
運行時錯誤:0000005:訪問衝突讀取位置0xCDCDCDE1中的file.exe在0x00DAC616
第一次機會異常。
下面是代碼:
#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;
}
可能是什麼錯誤的代碼?
你忘了問一個問題。你嘗試調試什麼? – aslg
你是否真的需要實現自己的鏈表? ** vs ** std :: list –
aslg
對於第一個問題,我放棄了它,因爲我必須確保它確實工作;第二,我必須實現我自己的鏈表。 – Oguz