#include
#include
#include
#include
#include
using namespace std;
long nextprime( long lastprime, const char* filename);
int main()
{
const char* filename = "D:\\JunkData\\primes.txt";
int nprimes = 0;
int count = 0;
long lastprime = 0;
int tries = 0;
cout<<"How many primes would you like (at 1east 3)? : ";
do
{
if(tries) //if(tries==0) 为falst,不执行;
cout<
if ( ++tries == 5)
{
cout<
}
} while ( nprimes < 3);
ifstream inFile; //create input file stream object;
inFile.open(filename); //open the file as input stream;
cout<
if ( !inFile.fail()) //如果打开文件成功;
{
do
{
inFile >> lastprime;
cout<<(count++ % 5 == 0 ? "\n" : " " )<< setw(10)<
inFile.close(); //关闭文件;
}
inFile.clear(); //清除文件;
try
{
ofstream outFile;
if ( count == 0)
{
outFile.open(filename);
if ( !outFile.is_open()) //如果不能打开文件
throw ios::failure( string("Error opening output file") +
string(filename) + string(" in main()"));
outFile <<" 2 3 5";
outFile.close();
cout<
count = 3;
}
while(count < nprimes)
{
lastprime = nextprime(lastprime, filename);
outFile.open(filename, ios::out | ios::app);
if ( !outFile.is_open())
throw ios::failure( string("Error opening output file") +
string(filename) + string(" in main()"));
outFile<<" "<
cout<< (count++ % 5 == 0 ? "\n" : " ") << setw(10) <
cout<
}
catch (exception& ex)
{
cout<
}
}
long nextprime( long lastprime, const char* filename)
{
bool isprime = false;
long aprime = 0;
ifstream inFile;
for ( ; ; )
{
lastprime += 2;
long limit = static_cast
inFile.open(filename);
if ( !inFile.is_open())
throw ios::failure( string("Error opening input file") +
string(filename) + string(" in nextprime()"));
do
{
inFile >> aprime;
} while (aprime <= limit && !inFile.eof() &&
(isprime = lastprime % aprime > 0));
inFile.close();
if (isprime)
return lastprime;
}
}
这个是读取D:\JunkData\primes.txt的文件里的质数,比如你输入10个,他就会从文件里读取10个;
以下是把质数写如文件文本的代码
#include
#include
using namespace std;
int main()
{
const int max = 100;
long primes[max] = {2, 3, 5};
int count = 3;
long trial =5;
bool isprime = true;
do
{
trial += 2;
int i =0;
do
{
isprime = trial % *(primes +i) > 0;
} while (++i < count && isprime);
if (isprime)
*(primes + count++) = trial;
} while (count < max);
ofstream outFile("D:\\JunkData\\primes.txt");
for (int i = 0; i < max; i++)
{
if(i % 5 ==0)
outFile<
}
return 0;
}
通过MFC提供的CStdioFile 的方法 ReadString 可以通过它来读取每一行数据,接着使用你的算法就可以了。