0

我一直在试图弄清楚如何将程序输出镜像到 .txt 文件以及控制台。我对此比较陌生,所以我迷路了。请帮忙,这是我到目前为止所拥有的。

#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>

using namespace std;

bool isPrime (int);

int main ()
{
    int numbers;
    ifstream inputFile;
    //open the file
    inputFile.open("22.txt");
    //output to file
    ofstream outFile;
    outFile.open("PrimeNumbers.txt");
    while(inputFile >> numbers)
        if(isPrime(numbers))
            outFile << numbers << endl;
            cout << numbers << " is a prime number." << endl;
} //end of main function
//function formula
bool isPrime (int num)
{
    int count=0;
    for (int numb=2; 
        numb<=num/2; 
        numb++)
    {
        if(num%numb==0)
            count++;
    }
    if (count>0)
        return false;
    else
        return true;
}
4

1 回答 1

1

对我来说突出的一个错误是:

while(inputFile >> numbers)
    if(isPrime(numbers))
        outFile << numbers << endl;
        cout << numbers << " is a prime number." << endl;

您没有任何块(由大括号定义),因此此代码段等效于:

while(inputFile >> numbers)
{
    if(isPrime(numbers))
    {
        outFile << numbers << endl;
    }
    cout << numbers << " is a prime number." << endl;
}

看看“cout”语句如何不受条件影响?你想写的是:

while(inputFile >> numbers)
{
    if(isPrime(numbers))
    {
        outFile << numbers << endl;
        cout << numbers << " is a prime number." << endl;
    }
}

(另外,如果您需要更多帮助,请参阅我在您的问题下方的评论,要求对问题进行更准确的定义)

于 2012-11-14T05:45:17.883 回答