无法输出我写入文件的内容

时间:2013-04-18 21:19:31

标签: c++ file-io

#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;
}

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

1 个答案:

答案 0 :(得分:2)

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

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

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