C ++:简单的fstream没有写入输出文件(不确定它是否正在输入文件)

时间:2014-02-26 04:17:08

标签: c++

我有一个测试文件(" InputFile.txt")保存了一些随机信息以及一个空白输出文件(" output.txt")。当我调试程序并检查输出文件时,它仍然是空白的。

应该" output.out" be" output.txt" (第25行)?我有问题,因为我有" InputFile.txt"作为if语句第22行的cstring? 这是正确的吗?到目前为止,我对fstream有点失落,请帮忙。

我的代码:

#include<fstream>
#include<string>
#include<iomanip>
#include<iostream>

using namespace std;

int main()
{
    ifstream InputFile;
    ofstream OutputFile;

    string lastName, firstName, fileName,
        line;
    int creditHours, state;
    int tuition;
    bool valid = false;

    do{
    cout << "Input file name (.txt): ";
    cin >> fileName;
    if(fileName == "InputFile.txt")
    {
        InputFile.open("InputFile.txt");
        OutputFile.open("output.out");
        valid = true;
    }
    else{
        cout << "Invalid file name/type." << endl;
    }
    }while(valid == false);




    OutputFile << "Last Name: " << '   ' << "First Name: " << '   '
        << "Credit Hours: " << '   ' << "Tuition Amount: " << endl;
    while(!InputFile.eof()){

    getline(cin, line);
    InputFile >> firstName >> lastName >> creditHours >> state;
    if(state == 1)
    {
        tuition = (creditHours * 350);
    }
    else
    {
        tuition = (creditHours * 570);
    }
    OutputFile << lastName << '   ' << firstName << '   ' 
        << creditHours << '   ' << tuition << endl;
    }



    InputFile.close();
    OutputFile.close();

    return 0;
}

1 个答案:

答案 0 :(得分:2)

试试这个

ifstream inFile;
ofstream outFile;

并打开文件进出模式,如

inFile.open("InputFile.txt", ios::in);
outFile.open("Output.txt",ios::out);

之后读取Inputfile数据并将其写入输出文件

while (!inFile.eof()) {
inFile >> firstName >> lastName >> creditHours >> state;
outFile << firstName << " " << lastName<<"  "<<creditHours<< " " <<state<<"  "<< endl;
}

并以循环方式应用逻辑