0

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
Fiunkk
  • 1
  • 2
  • Change `fin >> num;` to `if (!(fin >> num)) break;` Change the loop condition to `while (fin)` – Barmak Shemirani Nov 06 '17 at 06:23
  • I'm not sure if this would work in the solution. I need to output the number before the loop for the first value, while also outputting for the following numbers in the loop. – Fiunkk Nov 06 '17 at 06:39
  • I don't see any endless loop of 0 and 2 here, worked fine on my system, by the way you missed a semi colon(;) in line 35 – HMD Nov 06 '17 at 07:01
  • Thank you for the help, there must be a problem on my end – Fiunkk Nov 06 '17 at 07:23
  • I am sure you are wrong. See other questions on this site: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125). `fin >> num` can fail and you need to check it. – Barmak Shemirani Nov 06 '17 at 19:32
  • I may have misunderstood. Which 'fin >> num' are referring to? The first before the loop allows me to check it against my while condition, and the second inside the loop takes the next number on the list. – Fiunkk Nov 08 '17 at 08:06

0 Answers0