1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstring>
#include "util.h"
using namespace std;
int findSize(char numOfNames[])
{
ifstream names(numOfNames);
char name[255];
int count;
while(names.getline(name,255))
{
count++;
}
return count;
}
//Add printNames
void printNames(char **name,int size)
{
ifstream names(*name);
char arr[255];
while(names.getline(arr,255))
{
cout << name << endl;
}
return;
}
//Add copyNames
bool copyNames(char *nameOfFile, char **arrOfNames, int size)
{
ifstream file;
file.open(nameOfFile, ios::in);
//read the file into the arrays
for (int i = 0; i < 255; i++)
{
file >> arrOfNames[i];
}
return true ;
}
char **createArray(int size)
{
if(size < 0 || size > 1000)
return NULL;
char **array = new char*[size];
return array;
}
void deleteArray(char **array, int size)
{
for(int i=0; i<size; i++)
delete[](array[i]);
delete[](array);
return;
}
const int MAX_STRING_LENGTH = 255;
int main(int argc, char* argv[])
{
int size=0;
char **names=NULL;
char *fileName = new char[MAX_STRING_LENGTH];
//check if a filename is given
if(argc > 1)
strcpy(fileName, argv[1]);
else
strcpy(fileName, "input.txt"); //default filename
//Determine how big to make the array
//This is a fancy way of checking the return value
// at the same time when the function is called
if( (size=findSize(fileName))==-1 )
{
cout << "An error occured...exiting\n" << endl;
return EXIT_FAILURE;
}
//Create the array - allocating memory
names = createArray(size);
//Copy the names into the array from the file
if(!copyNames(fileName, names, size))
return EXIT_FAILURE;
char array[255];
// define file class
ifstream file;
file.open("input.txt", ios::in); //file.txt is the file you wanna open, ios::in means input file
//now read the file into the arrays
for (int i = 0; i < 255; i++) // a simple loop which counts to 3
{
file >> array[i];
}
cout << "The names in the file are:\n------------" << endl;
cout << names[0] << endl;
//Print the names in the array
printNames(names, size);
//Delete the array - freeing the memory
deleteArray(names, size);
cout << "------------\nGoodbye!" << endl;
return EXIT_SUCCESS;
}
|