Infile, Outfile help!

Pages: 12
bump....
Ok ... I took a look.
Unfortunately as I read through the code I reformatted some of it, tweaked it here and there, so by the time I eventually ran the thing, my code no longer resembles the original very much.

On the other hand - I do now understand this problem pretty well, so please vinci65812301, if you'd like to post the very latest version of your code, I'll take another look.

One problem is here:
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
void constructInfile (fstream& inFile, char fileName[])
{
    inFile.open (fileName, ios::out);

    if (!inFile)
    {
        cout << fileName << " cant be created for write"
        << endl;

        exit (-1);
    }

    int size = rand() % 100;
    
	for (int i = 0; i < size; i++)
	{
		inFile << rand() << "\t"
		<< "// Number" << i << endl;
	}

    cout << "written to outfile successfully" << endl;

    inFile.close();

}


Lines 81,82 are outputting to the file something like this:
6334	// Number0
26500	// Number1
19169	// Number2
15724	// Number3
11478	// Number4
29358	// Number5

But when the data is read back in here:
101
102
103
104
105
106
    cout << "Begin file to array" << endl;
    int i = 0;
    while (inFile >> n[i].no)
    {
        ++i;
    }

The program will read the first integer into n[0].no
and then attempt to read // into the next integer. Because it found a forward slash instead of an integer, the input fails and the loop ends.



Edit: One more comment. I see no reason for the fstream to be passed as a parameter to any of the functions. Each function receives the name of the file, which is all that is needed in order to create a local ifstream or ofstream as required.

For example I modified the functions like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void constructfile (const std::string & fileName)
{
    std::ofstream outfile(fileName);

    if (!outfile)
    {
        std::cout << fileName << " cant be created for write\n";
        exit (1);
    }

    int size = rand() % MAX;
    
    for (int i = 0; i < size; i++)
    {
        outfile << std::setw(7) << rand() << '\n';
    }

    if (outfile)
        std::cout << size << " integers written to outfile " << fileName << " successfully\n";
    else
        std::cout << "Error creating outfile" << fileName << "\n";
}


and this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int constructArray (const std::string& fileName, Number n[], int maxsize)
{
    std::ifstream inFile(fileName);

    if (!inFile)
    {
        std::cout << fileName << " cant be accessed for array creation.\n";
        exit (1);
    }
    
    std::cout << "Begin file to array\n";
    int i = 0;
    while ((i < maxsize) &&  (inFile >> n[i].no))
    {
        ++i;
    }

    std::cout << "File to array transfer: " << i << " numbers successfully read.\n";

    return i;
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12