i-- not working as update in for loop???

code:

//Kristen Korz
//CIS 22A
//This program reads an input file and writes the words in reverse order to an output file.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
//create and link input...
ifstream inputFile;
inputFile.open("input.txt");
//...and output files
ofstream outputFile;
outputFile.open("output.txt");

//error message for file open fail
if (inputFile.fail())
cout << "Error opening the file.\n";

//constant for max size
const int MAXSIZE = 1024;
//string array and temporary-use string
string words[MAXSIZE];
string str; //note: variables will be used for output loops too

//read words from input file
for (int i = 0; (inputFile >> str) && (i < MAXSIZE); i++)
{
words[i] = str;
}
inputFile.close();

//for showing if read correctly
cout << endl;
for (int i = 0; i < MAXSIZE; i++)
cout << words[i] << " ";

//for writing in reverse word order to output file
for (int i = MAXSIZE; (outputFile << str) && (i >= 0); i--)
{
words[i] = str;
}
outputFile.close();

//for showing if written correctly
for (int i = MAXSIZE; i >= 0; i--)
{
cout << words[i] << " ";
}

system("pause");
return 0;
}

terminal output:

This is my test file. I hope this works.
works. works. works. works. works. works. works. works. works. works. works (etc.)

I need the latter half of the output to read:
works. this hope I file. test my is This
Last edited on
Your problem with the output comes from this code:
for (int i = MAXSIZE; (outputFile << str) && (i >= 0); i--)

The last word read from the input file is "works." So the above code will continuously write that word into the output file 1024 times.

More mistakes:

1
2
3
4
//for showing if read correctly
cout << endl;
for (int i = 0; i < MAXSIZE; i++)
    cout << words[i] << " ";


Did you enter 1024 words exactly?
Same problem with this code:

1
2
3
4
for (int i = MAXSIZE; i >= 0; i--)
{
    cout << words[i] << " ";
}


1
2
3
4
for (int i = MAXSIZE; (outputFile << str) && (i >= 0); i--)
{
    words[i] = str;
}


Check this out:
http://www.cplusplus.com/doc/tutorial/arrays/
Topic archived. No new replies allowed.