请教各位高人,用C++读取某txt文件内的数值作为范围并求此范围内的质素怎么实现?

2024-12-23 02:39:37
推荐回答(2个)
回答1:

#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< cin>> nprimes;
if ( ++tries == 5)
{
cout< return 1;
}
} 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)< } while (count < nprimes && !inFile.eof());

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< lastprime = 5;
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<<" "< outFile.close();
cout<< (count++ % 5 == 0 ? "\n" : " ") << setw(10) < }

cout< return 0;

}
catch (exception& ex)
{
cout< return 1;
}

}

long nextprime( long lastprime, const char* filename)
{
bool isprime = false;
long aprime = 0;
ifstream inFile;

for ( ; ; )
{
lastprime += 2;

long limit = static_cast(sqrt(static_cast(lastprime)));

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< outFile << setw(10) << *(primes +i);
}

return 0;
}

回答2:

通过MFC提供的CStdioFile 的方法 ReadString 可以通过它来读取每一行数据,接着使用你的算法就可以了。