New to file I/O and c++ in general, would greatly appreciate any help or if someone can point me in the general direction.
The goal is to read in a file where the records are confined by a pair of {}. However, one record is not necessarily on one line in the input file. Next you remove white space and any duplicate records. The unique records are written on to a plain text file.
For example:
input1.txt
{id:1234567,first:Mary,last:Green}
{id:1234568, first:Peter, last:Morgan}
{id:1234567, first:Mary, last:Green}
output1.txt
{id:1234567,first:Mary,last:Green}
{id:1234568,first:Peter,last:Morgan}
input2.txt
{id:1234567,
first:Mary,last:Green,GPA:4.0} {id:1234568, first:Peter,
last:White , GPA:3.8}
{id:1234567, first:Mary, last:Green, GPA:3.9}
output2.txt
{id:1234567,first:Mary,last:Green,GPA:4.0}
{id:1234568,first:Peter,last:White,GPA:3.8}
{id:1234567,first:Mary,last:Green,GPA:3.9}
This is my code so far. It only works for input1.txt, because I do not know how to parse an input file into seperate records based on a pair of {}. I only know how to parse a file by lines using getline().
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
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string arr[100]; // creates array to hold names
int size = 100;
short loop = 0; //short for loop for input
string line; //this will contain the data read from the file
ifstream myfile("input1.txt"); //opening the file.
ofstream myOutput("output1.txt");
if (myfile.is_open()) //if the file is open
{
while (!myfile.eof()) //while the end of file is NOT reached
{
getline(myfile, line); //get one line from the file
for (int i = 0; i < line.length(); i++)
{
if (line[i] == ' ') line.erase(i, 1); //erase if there is a white space
}
arr[loop] = line;
loop++;
}
//get rid of duplicates
for (int i = 0; i < size - 1; i++)
{
// cout << myArr[i] << '\n';
for (int j = i + 1; j < size; j++)
{
// cout << '\t' << myArr[j] << '\n';
if (arr[i] == arr[j]) // then this is a duplicate
arr[j] = "";
}
}
//cout
for (int i = 0; i < size; i++)
{
cout << arr[i] << endl; //and output it
}
//output in txt file
if (myOutput.is_open())
{
for (int i = 0; i < size; i++)
{
myOutput << arr[i] << "\n";
}
myOutput.close();
}
myfile.close(); //closing the file
}
else cout << "Unable to open file"; //if the file is not open output
system("PAUSE");
return 0;
}
|