I'm relatively new to C++ so please excuse the use of namespace std. I'm trying to read a numeric value from a file, and determine its prime factors. Despite not failing it will ignore input, displaying an endless loop of '0' and '2is a prime number'. Below is both my code and text file.
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int div = 0, num = 0, count = 0;
string inputFile;
ifstream fin;
cout << "Enter input file name: ";
getline(cin, inputFile);
fin.open(inputFile.c_str());
if (fin.fail())
{
cout << "Bad file.\n";
cin.ignore();
getchar();
exit(0);
}
fin >> num;
cout << left << setw(12) << "Number" << setw(15) << "Prime Factors\n"
<< "---------------------------\n"
<< setw(12) << num << endl;
while (!fin.eof())
{
div = 2;
count++;
cout << setw(15) << num;
if (num < 0)
cout << "Can't do negative numbers\n"
else
{
cout << div;
while (div <= num / 2)
{
if (num % div == 0)
{
num = num / div;
cout << div;
}
else
div++;
}
}
if (div >= num / 2)
cout << "is a prime number\n";
fin.ignore(10, '\n');
fin >> num;
cout << setw(12) << num << endl;
}
if (count == 0)
cout << "No data was processed, data file is empty.\n";
cin.ignore(10, '\n');
getchar();
return (0);
}
Input.txt (Ended with a singular blank line for EoF):
348
23