2
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
ofstream fout1;
ofstream fout2;

string fnameOdd;
string fnameEven;
int x;
int numEven(0);
int numOdd(0);

cout << "Enter name of file for odd integers: ";
getline(cin, fnameOdd);

fout1.open(fnameOdd.c_str(), ios::out);

cout << "Enter name of file for even integers: ";
    getline(cin, fnameEven);

fout2.open(fnameEven.c_str(), ios::out);

if(!fout1.is_open())
{
    cerr << "Unable to open file" << fnameOdd << endl;
    exit(10);
}

if(!fout2.is_open())
{
    cerr << "Unable to open file" << fnameEven << endl;
    exit(15);
}

cout << "Enter list of odd and even integers (followed by 0): " << endl;
cin >> x;
while (x != 0)
{

if (x % 2 == 0)
{
    numEven++;
}
else
{
    numOdd++;
}
}
fout1 << numEven;
fout2 << numOdd;

cout << "File " << fnameOdd << " contains " << numOdd << " odd integers. " <<endl;
cout << "File " << fnameEven << " contains " << numEven << " even integers. " <<endl;


fout1.close();
fout2.close();

return 0;
}

我无法将任何内容输出到屏幕上,没有任何事情发生,只是输入文件名和整数。我不确定如何将我写的内容输出到文件中,阅读我的书也无济于事。

4

1 回答 1

2

您忘记了您的输入语句也cin >> x;需要进入循环内部

cin >> x;
while (x != 0)
{
    if (x % 2 == 0)
    {
        numEven++;
    }
    else
    {
        numOdd++;
    }
    cin >> x; // new line here
}

在输入 x 的第一个值后编写它的方式,它永远不会再次更改它的值。所以while循环永远不会结束。这就是为什么你没有看到任何输出。

于 2013-04-18T21:21:38.997 回答