输出文件到.txt和控制台c ++

时间:2012-11-14 05:38:56

标签: loops file-io console text-files primes

我一直试图弄清楚如何将程序输出镜像到.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;
}

1 个答案:

答案 0 :(得分: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;
    }
}

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