Data Structures and Algorithms Discussion Board
September 07, 2010, 03:05:24 PM *
Welcome, Guest. Please login or register.
Login with username, password and session length
News: Looking for a reliable webhosting provider? Read HostGator review to find 7 arguments in support of HostGator.
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: input/ output to file  (Read 1754 times)
*Pali*
Guest
« on: February 22, 2009, 03:47:33 PM »

i want to do a program that:
* Opens a file named lettergrades.txt on the C drive. (lettergrades.txt contains a single line with four characters in it. Each character is either an A, B, C, D or F. Each character is separated by a space.)
*Checks to make sure that file is open before reading from it, otherwise displays a useful message.
*Reads in all the grades.
* Determines the point value of the letter grade. A = 4.0, B = 3.0, C = 2.0, D = 1.0, F = 0.0.
*Closes the file.
*Adds all points together and divides by 4.
*Displays the grade point average to the screen.

can anyone explain to me what i have to do, PLEASE!!!!
this is what i have  Huh Huh

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
   
    ifstream infile;
    ofstream outfile;
    char lettergrade[4];
    double average;
    infile.open ("C:// lettergrades. Txt");
   
    infile >> lettergrade;
    infile >> average;
    while ( !infile.eof())
   
    infile >> lettergrade >> average;
    outfile << lettergrade << " " << average/4 << endl;
   
    outfile.close();
   
       
    system("PAUSE");
}

 
 



Logged
Denis
Newbie
*

Rating: 0
Offline Offline

Posts: 21


« Reply #1 on: February 23, 2009, 12:02:58 AM »

Try this code:
Code:
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{

ifstream infile;
char lettergrade;
double pointvalue;
double average = 0;

infile.open ("C:\\lettergrades.txt");
if (infile.fail()) // in case file can't be opened
cout << "Failed to open the file" << endl;
else
{
while (!infile.eof())
{
// read letter grade
infile >> lettergrade;
// determine the point value
switch (lettergrade)
{
case 'A':
pointvalue = 4.0;
break;
case 'B':
pointvalue = 3.0;
break;
case 'C':
pointvalue = 2.0;
break;
case 'D':
pointvalue = 1.0;
break;
case 'F':
pointvalue = 0.0;
break;
}
// add to average
average += pointvalue;
}
// close INPUT file
infile.close();
// display an average
cout << "Average: " << (average / 4) << endl;
}

system("PAUSE");
}

and the lettergrades.txt is:

A F B C

What is your mistakes:
1) use back slashes in infile.open("...;
2) you don't need ofstream (output file stream), until you decide to WRITE to file;
3) you missed a code converting the letter grade to the point value;
Logged
Pages: [1]
  Print  
 
Jump to:  

 
Partners Ads        queen mattress