Pointers/Linked Lists in C++

  • Comp Sci
  • Thread starter vermin
  • Start date
  • Tags
    C++
In summary: For example, the CDT or C++ Development Toolset. If you are not using an IDE, you are missing out on a LOT of functionality that will make your life much easier.In summary, the conversation is about a programming assignment to write a program that takes a text file with letters and integers and inserts them into a linked list using pointers. The code written by the speaker successfully decodes the message from the file, but they are experiencing issues with the program freezing in subsequent attempts. They are seeking advice on how to debug the code, as they do not have access to a debugger. The other speaker suggests using print statements or searching for an IDE that includes a debugger.
  • #1
vermin
22
0

Homework Statement



The program is supposed to take in a text file that has a letter and an integer on each line separated by a space. The integer is the order the letter is supposed to come in. The assignment is to write a program that takes the letters and inserts them using pointers into a linked list. For example;

1 e
3 c
0 b
4 h
2 a

should spell out "beach".

Homework Equations



n/a

The Attempt at a Solution



The below code is what I wrote - it will successfully take a file in and decode a message from it once - but attempts after that will cause it to freeze. It gets stuck in an infinite loop (?) somehow in the "while (infile.get(letter))..." loop.

Since it's compiling and not crashing I'm getting no feedback on what's going wrong. All I can suppose is that I'm not handling the pointers properly, but I have no idea in which way.

Code:
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

struct Node {
  int place;
  char letter;
  Node *next;
};

class secretMsgs {
public:
    void addAtHead(Node* &h, char letterGiven, int placeGiven);
    void insertInOrder(Node* &h, char letterGiven, int placeGiven);
    void readList(Node* &h);
	void deleteList(Node* &h);
    string getPath();
private:
    const char SPACE = ' ';
	const int SCREEN_CHECK = 73;
	int charCount = 0;
};


int main() 
{
    string filename;
    char letter;
	int place;
	char goAgain = 'y';
	
	ifstream infile;
    
    secretMsgs sMsg;
    
    Node *head = new Node;
	
	while (goAgain=='y') {
		cout << "Enter filename (with path): ";
		cin >> filename;
        infile.open(filename);
		if (!infile.fail()) {
			
			while (infile.get(letter)) {
                infile >> place;
                infile.ignore();
                sMsg.insertInOrder(head, letter, place);
			}
            infile.close();
			             
			cout << "Here's the decoded message: " << endl;
			sMsg.readList(head);
			
			sMsg.deleteList(head);
			
			cout << "Do it again on another file? (y/n)";
			cin >> goAgain;
		} else {
			cout << "Cound not read file.\n";
            infile.close();
		}
	}
	
    return 0;
	
}

// find the head, insert new data, replace the head
void secretMsgs::addAtHead(Node* &h, char letterGiven, int placeGiven) {
  Node* ptr;
  if (h==nullptr) {
	h = new Node;
	h->place = placeGiven;
    h->letter = letterGiven;
	h->next = nullptr;
  } else {
	ptr = new Node;
	ptr->place = placeGiven;
    ptr->letter = letterGiven;
	ptr->next = h;
	h = ptr;
  }
}

void secretMsgs::deleteList(Node* &h) {
	Node* ptr;
	Node* deleteMe;
	ptr = h;
	while (ptr->next!=nullptr) {
		deleteMe = ptr;
		ptr = ptr->next;
		delete deleteMe;
	}
	delete ptr;
}

// crawls through list starting at head and inserts letter, place
// in order (after next highest 'place')
void secretMsgs::insertInOrder(Node* &h, char letterGiven, int placeGiven) {
	if (h==nullptr || h->place >= placeGiven) {
		addAtHead(h, letterGiven, placeGiven);
	} else {
		Node* ptr;
		Node* insert = new Node;
		insert->place = placeGiven;
		insert->letter = letterGiven;
		insert->next = nullptr;
		ptr = h;
		while (ptr->next!=nullptr && ptr->next->place < placeGiven) {
			ptr = ptr->next;
		}
		if (ptr->next!=nullptr) {
			insert->next = ptr->next;
		}
		ptr->next = insert;	
	}
}

// print the entire chain, wrap @ 80 cols by replacing spaces with endl;
void secretMsgs::readList(Node* &head) {
	charCount = 0;
    Node* ptr = new Node;
    ptr = head;
    while (ptr!=nullptr) {
		if (charCount>=SCREEN_CHECK && ptr->letter==SPACE) {
			cout << endl;
			ptr = ptr->next;
			charCount = 0;
		}
        cout << ptr->letter;
        ptr = ptr->next;
		charCount++;
    }
	cout << "\n";    
}

any advice appreciated, thank you..
 
Physics news on Phys.org
  • #2
Have you heard about debuggers? Using a debugger to trace the code step by step will help you find the error. Or set the breakpoints in your code.

Alternatively, you can go the old way - insert some cout << "I am here!" lines in your code to localize where the program gets stuck.

These methods are universal and they will help you regardless of what the problem is. The sooner you master them, the better for you.

Disclaimer: I didn't even tried to analyze your code. Debugger is a fishing rod, not a fish.
 
  • #3
yeah don't really have access to a debugger. I've tried using cout messages, that's how I knew it was getting stuck on that loop.
 
  • #4
You can make it print pointers as hex values, to see if they are changed as expected.
 
  • #5
vermin said:
yeah don't really have access to a debugger.
That is very dubious. What compiler / what operating system are you using? If you are using an IDE, the debugger is almost inevitably an integral part of the IDE. If you are using a command line compiler you almost inevitably have a debugger that goes along with that compiler. Debuggers are a programmers best friend.
 
  • #6
Try searching for Eclipse or Netbeans. I prefer Eclipse because it will help to import different utilities depending on what you are trying to do.
 

1. What are pointers and how are they used in C++?

Pointers are variables that store the memory address of another variable. They are used in C++ to indirectly access and manipulate data stored in memory, rather than directly accessing the data itself.

2. How do you declare and initialize a pointer in C++?

To declare a pointer in C++, you use the asterisk symbol (*) before the variable name. For example, int *ptr; declares a pointer variable named "ptr" that points to an integer. To initialize the pointer, you can either assign it the address of another variable, or use the new keyword to dynamically allocate memory for the pointer.

3. What is a linked list and how does it differ from an array?

A linked list is a data structure that consists of a series of nodes that are connected by pointers. Each node contains both data and a pointer to the next node in the list. Unlike an array, a linked list does not store data in contiguous memory locations, allowing for more flexibility in adding, removing, and rearranging data.

4. How do you insert or delete nodes in a linked list?

To insert a node into a linked list, you first create a new node and assign its data and pointer values. Then, you adjust the pointers of the surrounding nodes to point to the new node. To delete a node, you adjust the pointers of the surrounding nodes to bypass the node you want to remove, and then free the memory allocated for the node.

5. What are some advantages of using linked lists over arrays?

Linked lists have several advantages over arrays, including the ability to insert and delete data at any point in the list without having to shift other elements, efficient memory usage for large data sets, and the ability to easily create and manipulate complex data structures such as trees and graphs.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
3K
Back
Top