Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Help in Combining Two Text files

$
0
0
I am trying to combine two text files, and somehow it won't merge and arrange them in alphabetical format.

contacts1.txt
Engstrom, John john.engstrom@lifetech.com
Patel, Elsa elsa.patel@sanjoseca.gov
Sabandal, Christian csabandal@as39.navy.mil

contacts2.txt
Delacruz, Edwinjared edwinjared.delacruz@va.gov
Singh, Shammi shammi.singh.fj@navy.mil

The output should be:
allContacts.txt
Delacruz, Edwinjared edwinjared.delacruz@va.gov
Engstrom, John john.engstrom@lifetech.com
Patel, Elsa elsa.patel@sanjoseca.gov
Sabandal, Christian csabandal@as39.navy.mil
Singh, Shammi shammi.singh.fj@navy.mil



Here's what I Have so far

#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <string>

using namespace std;

bool sortedByName(string FileName); 

void merge(string name1, string name2, string name3);

int main(){
string name1, name2, name3;
cout << "This program can combine two .txt files with e-mail contacts. The files need to be alphabetically arranged in order to work." << endl; 
cout << "What are the files you want to merge? (limited to two files only)" << endl;
cin >> name1;
cin >> name2;

if(sortedByName(name1))
{ 
if(sortedByName(name2))
{
cout << "Where do you want your arranged merged file to be stored at?" << endl;
cin >> name3;
merge(name1, name2, name3);
}
else cout << "Please arrange your files alphabetically by last name first. Then, re-run the program." << endl;
}
else cout << "Please arrange your files alphabetically by last name first. Then, re-run the program." << endl;




system("pause");
return 0;

}

bool sortedByName(string FileName)
{
bool sorted;
sorted = true;
string line1[256], line2[256];

ifstream inFile;
inFile.open(FileName);

inFile == line1;


while(sorted && !inFile.eof())
{
inFile == line2;
if(line1 < line2)
sorted = false;
else if(line1 > line2)
sorted = true;

}
inFile.close();
return sorted;

}

void merge(string name1, string name2, string name3)
{
string line1, line2;
ifstream inFile1;
ifstream inFile2;
ofstream outFile;

inFile1.open(name1);
inFile2.open(name2);
outFile.open(name3);

inFile1 >> line1;
inFile2 >> line2;

while(!inFile1.eof() && !inFile2.eof())
{
if(line1 > line2)
{
outFile << line1 << endl;
inFile1 >> line1;

}
else if(line1 < line2)
{ 
outFile << line2 << endl;
inFile2 >> line2;
}

}
if(inFile1.eof())
{
while(!inFile2.eof())
{	
outFile << line2 << endl;
inFile2 >> line2;
}
outFile << line2 << endl;
}
else if(inFile2.eof())
{
while(!inFile1.eof())
{
outFile << line1 << endl;
inFile1 >> line1;

}
outFile << line1 << endl;
}
inFile1.close();
inFile2.close();
outFile.close();

}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>