I've written a program for class that takes a text file, reads it, adds to it, and is supposed to be able to write to a new text file. I've been looking but can't find the correct code I'm looking for. Here is the code so far...
CODE
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <conio.h>
#include <windows.h>
using namespace std;
struct ListNode
{
string name;
double value;
ListNode *next;
//constructor
ListNode(string name1, double value1)
{
name = name1;
value = value1;
next = NULL;
}
};
int main()
{
int menuchoice;
do{
cout<<"\n";
cout<<"*********************************************** \n";
cout<<"* Choose the task from the menu * \n";
cout<<"* 1. Print Curent List * \n";
cout<<"* 2. Add to Current List * \n";
cout<<"* 3. Write List to New File * \n";
cout<<"* 4. Exit Program * \n";
cout<<"*********************************************** \n";
cin>>menuchoice;
switch (menuchoice)
{
case 1:
{
system("cls"); //clear screen
// Open the file
ListNode *numberList = NULL; // List of numbers
ifstream numberFile("data.dat");
if (!numberFile)
{
cout << "Error in opening the file of numbers.";
exit(1);
}
// Read the file into a linked list
double number;
string name, extra; // Used to read the file
while (getline(numberFile,name))
{
numberFile >> number;
getline(numberFile,extra);
//create a node to hold this number
//check to see if the file is empty
if (numberList == NULL)
numberList = new ListNode(name, number);
else
{
ListNode *nodePtr;
nodePtr = numberList;
while (nodePtr->next !=NULL)
nodePtr = nodePtr->next;
nodePtr->next = new ListNode(name, number);
}
}
system("cls"); //clear screen
// Traverse the list while printing
cout << endl << "The contents of the list are: " << endl;
ListNode *ptr = numberList;
while (ptr != NULL)
{
cout <<"Student Name : "<< ptr->name << "\n"; // Process node
cout <<"Final Grade : "<< ptr->value << "\n";
cout <<"\n";// Process node
ptr = ptr->next; // Move to next node
}
break;}
case 2:
{
system("cls"); //clear screen
string name1, name2;
double addgrade;
cout<<"Enter the Name of the Student you wish to add.\n";
cin>>name1;
cout<<" ";
cin>>name2;
cout<<"Enter the final grade \n";
cin>>addgrade;
{
ofstream File; //Names File as ofstream (for output to file)
File.open("data.dat",ios::app); //Reopens file to append, if you just used ios::out again, it would erase everything and rewrite the file
File << endl <<name1 <<" "<<name2<< endl; //Outputs to file
File << addgrade; //Outputs last line of file
File.close(); //Closes opened file
}
break;}
case 3:
{
system("cls"); //clear screen
break;}
case 4:
{
system("cls"); //clear screen
cout<<"WHERE ARE YOU GOING? \n";
break;}}}
while (menuchoice != 4);
return 0;
}
The file has this info in it...
CODE
Sarah Barnhill
78
John Simmons
84
Marshall Thornhill
92
Ollie Maynard
94
Michelle Pitchard
94
Thomas Norris
100
Can anyone help me out?
Thanks in advance!!!
-Adam