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
|
#include <iostream>
#include <fstream>
#include <cstring>
#include <sstream>
using namespace std;
//CONSTANTS
const int MAXCHAR = 300;
//STRUCT FOR A SONG SongType
struct SongType
{
char song[MAXCHAR];
char artist[MAXCHAR];
int songMin;
int songSec;
char album[MAXCHAR];
};
//FORWARD DECLARATIONS
int readData(istream & input, SongType anArray[]);
int
main()
{
SongType myCollection[MAXCHAR];
ifstream inFile;
ofstream outFile;
int songCount = 0;
inFile.open("songs.txt");
songCount = readData(inFile, myCollection);
for (int i = 0; i < songCount; i++) {
cout << myCollection[i].song << " "
<< myCollection[i].artist << " "
<< myCollection[i].songMin << " "
<< myCollection[i].songSec << " " << myCollection[i].album << endl;
}
}
bool
readOne(istream &is, SongType &result)
{
// Sample: Stereo Hearts;Gym Class Heroes;3;34;The Papercut Chronicles II
char ch;
string str;
istringstream ss;
is.get(result.song, MAXCHAR, ';');
is >> ch;
is.get(result.artist, MAXCHAR, ';');
is >> ch;
getline(is, str, ';');
ss.str(str);
ss >> result.songMin;
if (ss.fail()) return false;
getline(is, str, ';');
ss.str(str);
ss.seekg(0); // gotta reposition the stream to the beginning.
ss >> result.songSec;
if (ss.fail()) return false;
getline(is, str); // read the
strncpy(result.album, str.c_str(), sizeof(result.album));
result.album[sizeof(result.album)-1] = 0; // null terminate if it's the exact length.
return is.good();
}
//FUNCTION TO READ songs.txt INTO STRUCT SongType
//As arguments takes infile, and SongType Array
//INPUTS EMPLOYEE FILE DATA INTO ARRAYS and returns the number of items in the array
int
readData(istream & input, SongType anArray[])
{
SongType tmp;
int counter = 0;
while (readOne(input, tmp)) {
anArray[counter++] = tmp;
}
return counter;
}
|