Month: April 2010

C++ code

Doubly Linked List (C++)

This code is an implementation and test driver of a doubly linked list. This list is pointer based and uses dynamic memory. Sorted Doubly Linked List with Insertion and Deletion #include <iostream> #include <cstdlib> #include <string> using namespace std; class Dllist { private: typedef struct Node { string name; Node* next; Node* prev; }; Node* head; Node* last; public: Dllist() { head = NULL; last = NULL; } bool empty() const { return head==NULL; } friend ostream& operator<<(ostream& ,const Dllist& ); void Insert(const string& ); void Remove(const string& ); }; void Dllist::Insert(const string& s) { // Insertion into an Empty […]

C++ code

Open Text File the Right Way. (C++)

This code is a simple example of how to safely open a text file in C++. Notice the very important check that the file was opened correctly. This covers a range of errors,  most commonly file not found. // Read integers from file and print sum. #include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; int main() { int sum = 0; string word; ifstream inFile;"test.txt"); if (!inFile) { cout << "Unable to open file"; exit(1); // terminate with error } while (inFile >> word) { cout << word << " "; } inFile.close(); return 0; }