Task 1
Write a C++ function in which it reads namesfrom file “data.txt” into character array and remove
the repeating names. Write your updated names list in another file called “output.txt”
Example:
Data.txt
Hira
Ali
Ahmad
Imran
Ali
Warda
Annie
Ali
Kinza
Hira
Output.txt
Hira
Ali
Ahmad
Imran
Warda
Annie
Kinza
//After running the program get follow results in "output.txt"
#include <iostream>
#include <string.h>
#include <iomanip>
#include <fstream>
#define SIZE 6555//how many lines maximum file
using namespace std;
int main()
{
ifstream inp("data.txt");//Input file handling
if(!inp)
{
cout<<"Sorry file not found \n";
return 0;
}
char **names=(char**)malloc(sizeof(char*)*SIZE);
for(unsigned i=0;i<SIZE;i++)
names[i]=(char*)malloc(sizeof(char)*SIZE);
int sz=0;
char buf[50];
while(inp.good())
{
inp>>buf;
strcpy(names[sz],buf);
sz++;
}
ofstream out("output.txt",ios::trunc);
//check
for(unsigned i=0;i<sz;i++)
{
int cnthis=0;
for(unsigned j=0;j<sz;j++)
{
if(strcmp(names[i],names[j])==0)
cnthis++;//count for repeat
}
if(cnthis==1)
{
out<<names[i]<<"\n";
}
}
//Disalloc memory
for(unsigned i=0;i<SIZE;i++)
free(names[i]);
free(names);
inp.close();
out.close();
return 0;
}
Comments
Leave a comment