Files and Arrays

Hi, I just need some clarification on how to work files and how to pass an array function. Thanks for the help.

1) I am working with PC. Do I create the txt file manually?
2) How would I pass the array sort function?
3) In general how do files work?

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
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
using namespace std;

void Sort (int Array[10]) {
    int temp;
    for (int i = 0; i < 10; i++) {
        for (int j = i + 1; i < 10; i++) {
            if (Array[i] > Array[j]) {
                temp = Array[i];
                Array[i] = Array[j];
                Array[j] = temp;
            }
        }
    }
}

int main() {
    int ArrayF[10] = {0,0,0,0,0,0,0,0,0,0};

    ifstream ifs("integers.C:\myfile.txt");
    ofstream ofs("integersout.C:\myfile.txt");

    ifs.open("integers.C:\myfile.txt");
    ofs.open("integers.C:\myfile.txt");

    /*if((ifs == 0) || (ofs == 0)) {
        cout << "Not found, ending program!" << endl;
        return 0;
    }*/

    for (int i = 0; i < 10; i++) {
        ifs >> ArrayF[i];
    }

    for (int i = 0; i < 10; i++) {
        ofs << ArrayF[i] << endl;
    }

    ifs.close();
    ofs.close();
    return 0;
}
I don't quite see what you are trying to do here:
1
2
    ifstream ifs("integers.C:\myfile.txt");
    ofstream ofs("integersout.C:\myfile.txt");


I would expect to see something like this:
1
2
    ifstream ifs("C:\\myinputfile.txt");
    ofstream ofs("C:\\myoutputfile.txt");

Notice the '\' character must be doubled, otherwise the compiler treat it as an escape sequence (much like '\n' or '\t' for newline or tab).

Lines 21 and 22 will open the corresponding streams, so you don't also need lines 23 and 25.


Call the function like this: Sort(ArrayF);

Files tutorial:
http://www.cplusplus.com/doc/tutorial/files/
guess your input file is called integers and your output file integersout

in that case use:

1
2
    ifstream ifs("C:\\where_ever_it's_located\\integers.txt");
    ofstream ofs("C:\\where_ever_it's_located\\integersout.txt");


if these text files are in your project folder, you can just use the names without the path
Last edited on
Topic archived. No new replies allowed.