Dumb question

I need to take the following code from a previous assignment are rewrite it using void functions. The code is very simple...but I'm confused on where to get started on this.I'm just now sure how to write this using a void function(s). Could I get some pointers please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;

int main ()
{
ifstream InFile;  
ofstream OutFile;
int num;


InFile.open("E:\\CFiles\\DataFile2.txt");  //Opens input file
OutFile.open("E:\\Answers.txt");           //Opens output file

cout<<"The input file contains the following data "; //Output statement
InFile>>num; 

while (InFile) //While file is open
{
cout<<num<<" "; // Displays numbers on file
InFile>>num;    // Gets next value
}

InFile.close(); //Closes output file
InFile.clear();

}




I would turn your infile/outfiles into functions first. In fact, I use both of those functions for all my assignments. So, you would do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
void openInput()
{
     InFile.open("**YourFileHere**);
     if (InFile)
     {
           cout << "Input file opened correctly."  << endl;
     }
     else
     {
          cout << "Error opening input file."  << endl;
     }
} 


You can do the same thing with your output file. Then in your main program, you would only have
openInput();
where you currently have your other code. I don't know how much your teacher wants you to convert, but you could do the same thing with your output statement. You can make anything into a void function.
For your while loop, you just stick it all in a function, and then call the function instead of writing all that code in main.
I hope that helps.
:)
Last edited on
That's a great idea. My first attempt was rewriting the while loop as a void function, but that was a spectacular failure :)

That was my next thought. Thanks!
Better yet, impress your professor and make the void functions with parameters. Spooky, I know.

1
2
3
4
5
6
7
8
9
void openInput(string filename) {
    ifstream in(filename);
    if (in) {
        cout << "It worked." << endl;
    }
    else {
        cout << "It didn't open correctly." << endl;
    }
}


This is good so that you don't have to hard-code the filename into the function. Instead, it can be a variable that is received as input earlier on in the program like so:

1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
#include <iostream>
using namespace std;

int main() {
    string filename;
    cout << "Please enter the filename: ";
    getline(cin, filename);
    
    openInput(filename);
}
The only issue with your function LimeOats is that once the function finishes, the file is automatically closed.
Topic archived. No new replies allowed.