I wonder why this program does not do any changes to the text file that I am trying to modify.
Scenario: My program uses the Fstream header file, I declared infile as IFSTREAM and outfile as OFSTREAM. I simply want to transfer data from infile to outfile. The data is as follows;

Adam Larson 89 90

This data is saved in a text file manually created with Notepad. Furthermore, I also want to add the average of 89 and 90 into the outfile target file however, it doesn't do it. it does nothing at all. I also observed that there seems to be no data extracted at all using the infile variabe so nothing is being copied into the output file. here is my code;

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){

    ifstream infile;
    ofstream outfile;

    string fname, lname;
    int mathgrade, sciGrade;
    double average;

    //get data from Input file
    cout << "This program creates a copy of a student data file with average\n";
    infile >> fname >> lname;
    infile >> mathgrade >> sciGrade;
    average = (mathgrade + sciGrade) / 2;
    //copy data into Output file
    outfile << fname << " " << lname << " " << mathgrade << " " << sciGrade << " " << endl << "Average: " << average << endl;
    cout << "Done processing...\nCheck thie file for output: C:\Projects\C++\outfile.txt\n";
    return 0;

This program does not have any errors but does not do anything either.
What am I missing?

2 Years
Discussion Span
Last Post by markdean1989

Use an if statement and check to see if your files are actually open. You can do that with

    cout << "Input file not opened!";
    cout << "Output file not opened!";

If they weren't open then I would expect the input and output operators to throw an exception.

What output do you get if you use cout instead of outfile for the output stream? Do you get sensible values for mathgrade, scigrade, and average. Do you get any output? If not, then you may be getting a divide-by-zero or value overflow error. Also what compiler are you using, and if a GNU variant such as MingW, what compiler options did you use?


Thanks Nathan and @rubberman.
Good question, I have tried using cout to test whether or not there are any data from infile, there aren't. Nothing is displayed. As to what compiler I am using, not sure how to check that. I am just using MS Visual Studio 2013 Express for Desktop.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.