Post by Nicky Peter Hollyoake on Jan 30, 2009 21:28:01 GMT -5
Ok, I just wanted to show my achievement I've completed with pointers in C++. They are a pain getting use to, but pretty easy once you know. The example:
At the moment it reads seperate words I ain't quite got the hang of reading lines, I know its getline though.
- Nicky
/* Objective: Create file, close file, read file, output file on screen
include files */
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ()
{
// Create file
ofstream FileWrite ("Test.TXT");
cout << "Create text file named Test.TXT\n";
// Put text into the file
FileWrite << "This is line one of my text file\n";
FileWrite << "This is line two of my text file\n";
FileWrite << "This is the final line";
cout << "Writed text to the file\n";
// Close file
FileWrite.close();
cout << "Closed file\n";
// Open up the file now
ifstream FileRead ("Test.TXT");
cout << "Opened file to read from\n";
// Check for errors
if (not FileRead.is_open())
{
cout << "File doesn't exist.\n";
FileRead.close();
system("PAUSE");
}
cout << "No errors from the file\n";
// Setup our pointers
string *FileLine = NULL;
string *Backup = NULL;
// set the first pointer manuaully
Backup = new string[1];
FileLine = new string[1];
// Declare other vars
int FileLineCount = 0;
string Text; // Read text from the file
// Start our loop read to read the file
do
{
// Read a line from the file
FileRead >> Text;
if (Text != "")
{
// Delete and resize the backup pointer
delete[] Backup;
Backup = new string[FileLineCount];
// Keep a backup of the data
for (int i = 0; i < FileLineCount; i++)
{
Backup = FileLine;
}
// Delete and resize the pointer
delete[] FileLine;
FileLine = new string[FileLineCount + 1];
// Transfer the data back to the other pointer
for (int i = 0; i < FileLineCount; i++)
{
FileLine = Backup;
}
FileLine[FileLineCount] = Text;
FileLineCount++;
}
} while (not FileRead.eof());
// Close file
FileRead.close();
cout << "Done reading lines\nprinting them out ...\n\n";
// Output file
if (FileLineCount > 0)
{
for (int i = 0; i < FileLineCount; i++)
{
cout << FileLine << "\n";
}
}
// Delete our pointers to get our memory back
delete[] Backup;
delete[] FileLine;
}
At the moment it reads seperate words I ain't quite got the hang of reading lines, I know its getline though.
- Nicky