在将我写的内容输出到文件时遇到麻烦

having trouble outputting what i wrote to a file

本文关键字:文件 遇到 麻烦 输出      更新时间:2023-10-16
#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;
}

我有麻烦输出任何东西到屏幕,什么都没有发生,它只是输入文件名和整数。我不确定如何输出我所写的文件,阅读我的书没有帮助。

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

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

在输入x的第一个值之后,它不会再改变它的值。所以while循环永远不会结束。这就是为什么您没有看到任何输出。