Using the C++ standard library doubly linked-list template. Write a program that
ID: 665593 • Letter: U
Question
Using the C++ standard library doubly linked-list template.
Write a program that read real numbers from a file and inserted them into a singly-linked list in place using ascending order.
Algorithm:
prompt for the name of an ASCII text input file of real numbers (one per line)
a) create an output file name.
1. add "_out" to the end of the file name 2. before the file extension if there is an extension )
b) If this file cannot be opened for input (does not exist)
1. continue to prompt for the file name until one that exists is entered
define an instance of the C++ standard library list and an iterator for this list
read real numbers stored as ASCII text, one number per line from a file
a) numbers may be positive or negative
b) number may or may not have an embedded decimal point
c) numbers are not ordered in any way within the file
insert each real number into the list in ascending order
a) start at the beginning of the list
1. if list is empty insert at front
b) iterate thru list until a node of greater value or the end list is reached
1. if end-of-list insert at back 2. otherwise insert in place
close input file and open output file
traverse the linked list
a) start at the beginning and advance to each node until the list end is reached
b) write the real number in each node to output file
close output file
Explanation / Answer
#include <iostream>
#include <stdio.h>
#include <list>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream myfile;
while(true)
{
char fileName[20];
cout<<"Enter a valid input file name: ";
cin>>fileName;
myfile.open(fileName);
if(myfile.is_open())
break;
cout<<"The file You entered doesent exist ";
}
list<float> mylist;
list<float>::iterator it;
float number;
while(myfile>>number)
{
if(mylist.empty())
mylist.push_front(number);
else
{
it=mylist.begin();
while(*it<number and it!=mylist.end())
{
it++;
}
mylist.insert(it,number);
}
}
ofstream outFile;
outFile.open("out.txt");
it=mylist.begin();
while(it!=mylist.end())
{
outFile<<*it<<endl;
it++;
}
cout<<"Sorted numbers written to file ";
outFile.close();
myfile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.