Im trying to write a program that reads two files of no more than 20 integers then prints out the largest of the the two files, however after specifying the files i want read the program just sits there and continues to take input and doesn't do anything else. And yes this is an assignment, I just need to know why it stops running after inputing the filenames.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
usingnamespace std;
int main()
{
ifstream input1, input2;
int array1[20], array2[20], large1, large2, i=0, j=0, k, m;
string file1, file2;
cout<< "Enter the name of the first file you want read.\n";
cin >> file1;
cout<< "Enter the name of the second file you want read.\n";
cin >> file2;
input1.open(file1.c_str());
if(input1.fail())
{
cout<< "Your first file failed to open!\n";
exit(1);
}
do
{
input1>>array1[i];
i++;
}while(!input1.eof());
input1.close();
input2.open(file2.c_str());
do
{
input2>>array2[j];
j++;
}while(!input2.eof());
input2.close();
large1=array1[0];
for(k=1; k<i; k++)
{
if(array1[k]>large1)
{
large1=array1[k];
}
}
large2=array2[0];
for(m=1; m<j; m++)
{
if(array2[m]>large2)
{
large2=array2[m];
}
}
if(large1>large2)
{
cout<< "The largest integer in the two files is "<<large1<<".\n";
}
if(large1<large2)
{
cout<< "The largest integer in the two files is "<<large2<<".\n";
}
if(large1==large2)
{
cout<< "The largest integer in both files is "<<large1<<".\n";
}
return 0;
}
That wasn't it. For some reason, after I enter the name of the second file, the cursor moves down to the next line and sits there waiting for more input. I literally can continue typing and go on to a new line, but nothing else happens.
Check my post there. Basically, I think that your i and j variables end up 1 higher than what you think they are. That would mean you are trying to read more elements into the arrays than what they are meant to hold.
I thought i accounted for that when set k<i and m<j as opposed to setting it as k<=i and m<=j, since this is all just integers.
EDIT: I tried running it with k<i-1 and m<j-1, for sake of the doubt and it still wouldn't go past taking inputs., I even left it running for 15min to see if the program was taking along time. Note, i have 4gb of ram and a dual core processor so it shouldn't be that long for such a simple program.