First, I am in a C++ course and in my 7th week. I have a project that is due real soon but I am absolutely stuck on one part of an fstream console program. The part I'm having trouble in is reversing the numbers INTO a file I named "outFile_Reverse" from a file that contains the 5 numbers to be reversed in a file named "inFile_1".
The problem is that I get an unexpected output in my outFile_Reverse. After I run my program and open the outFile_Reverse file, it displays the last number 5 times when it should list them in reversed order!
What am I doing wrong? Perhaps my "for loop" logic is jacked??
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int main()
{
cout <<"\n\n\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-FSTREAM=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" <<endl;
cout <<"\nThis portion of the program will:\n\n" <<endl;
cout <<"1. Read 5 numbers FROM a text file" <<endl;
cout <<"2. Write the numbers in reverse order to a SECOND file" <<endl;
cout <<"3. Read 5 words in from a THIRD file" <<endl;
cout <<"4. Display results of words to the CONSOLE\n\n" <<endl;
ifstream inFile_1; // File we are reading the numbers from
ifstream inFile_2; // File we are reading the words from
ofstream outFile_Reverse; // File to use for reverse number output
string numbers_1; // Name of number txt file
string words_1; // Name of words txt fileLi
int num1, num2, num3, num4, num5; // Declaring variables to read numbers from stored file
string w1, w2, w3, w4 ,w5; // Declaring variables to read words from stored file
int counter;
inFile_1.open("numbers_1.txt", ios::skipws); // File stream variable to open numbers_1.txt file to read
inFile_2.open("words_1.txt" , ios::skipws); // File stream varibale to open words_1.txt file to read
outFile_Reverse.open("outFile_Reverse.txt"); // File stream variable to display reversed numbers into this outFile.
/***********************************************************************************************
outData file to display words_1 is not needed; displaying directly to console from inFile_2.
***********************************************************************************************/
for (counter = 0; counter < 5; counter++)
{
inFile_1 >> numbers_1;
}
outFile_Reverse <<"The numbers reversed are: ";
for (counter = 4 ; counter >= 0; counter--)
{
outFile_Reverse << numbers_1 <<" ";
}
cout <<"\nPlease check the outFile_Reverse file to verify the numbers have been reversed.";
inFile_1.close(); // Closes numbers_1.txt file
inFile_2.close(); // Closes words_1.txt file
outFile_Reverse.close(); // Closes outfile
cin.get();
cin.get();
return 0;
}
Lines 38-41: you are reading 5 numbers, but all of them into the same variable (numbers_1).
Lines 45-48: you are writing 5 numbers--all of them numbers_1. numbers_1 is an integer that
can store only one number at a time.