我对C ++比较陌生,所以请原谅使用命名空间std。我试图从文件中读取数值,并确定其主要因素。尽管没有失败,它将忽略输入,显示无限循环的“0' 0' 0和' 2是素数'。下面是我的代码和文本文件。
代码:
#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(以EoF的单数空行结尾):
348
23