out put file

If i write a program and want to print results of that program how does that work?
I am in an internet class and am more or less teaching myself as my professor gives us reading assignments then programming assignments and thats it. I have to write the code yet, but my current assignment is a postal scale thingy
I have to ask the user for dimensions and then the report tells which packages were accepted and how much shipping would be...I don't know exactly where or how in the program to put the code to read out to a file.I don't want the code written for me, just an explanation. Thanks
If you want your program to write an output file, you'll need to #include <fstream> in your program. When using fstream to write a file, an ofstream object must first be created. The syntax to create one states the ofstream keyword, followed by a space then your chosen name for the file object. Parentheses containing the text file name follow the file object name. For example, the following creates an output file object named obj then writes to a file called file.txt.

ofstream obj ("file.txt");

By default, the program will seek the file within the directory in which the program resides. If no file by the entered name is found, one will be created. If there is already a file by that name, it will be overwritten. fstream contains various methods to modify this default behavior, but I'll leave those for you to look up if you so desire. As a sample, the short program below will generate an output file called sky. Note that this example doesn't do anything but generate the file, and then close, so you'll have to look in the directory into which you compile the program for the result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <string>
#include <iostream>
using namespace std;

int main()
{
    string str ="\n\tI never saw a man who looked";
    str.append("\n\tWith such a wistful eye");
    str.append("\n\tUpon that little tent of blue");
    str.append("\n\tWhich prisoners call the sky\n");
    
    ofstream myfile("sky.txt", ios::app);
    
    if(!myfile) //Always check the file open.
    {
      cout<<"Error opening output file"<<endl;
      return -1;
    }
    myfile<<str<<endl; //Write the file.
    myfile.close();  //Always close the file.
    return 0;
}


I hope this helps.
Topic archived. No new replies allowed.