使用try-catch C ++进行文件处理

时间:2015-04-30 23:22:03

标签: c++ try-catch file-processing

我正在开展一个关于文件处理的项目。用户输入ID,小时和支付率。输出将是ID,小时,payrate和grosspay。我完成了那些部分。我真的需要帮助try和catch,用户输入非数字,项目拒绝并要求用户再次输入。 这是我到目前为止所得到的:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include "File.h"
#include <exception>
using namespace std;

void File::Create()
{
    ofstream outClientFile("payroll.txt", ios::out);

    if (!outClientFile)
    {
        cerr << "File could not be opened" << endl;
        exit(EXIT_FAILURE);
    }

    cout << "Enter employee ID, hours and payrate" << endl
        << "Enter end-of-file to end input.\n? ";

    while (cin >> id >> hours >> payrate)
    {
        try
        {
            outClientFile << id << ' ' << hours << ' ' << payrate << endl;
            cout << "? ";
        }
        catch (exception elementException)
        {
            cerr << ("Invalid input. Try again") << endl;
        }
    }
}
void outputLine(int, float, float, float);
void File::Read()
{
    ifstream inClientFile("payroll.txt", ios::in);

    if (!inClientFile)
    {
        cerr << "File could not be opened" << endl;
        exit(EXIT_FAILURE);
    }

    cout << left << setw(15) << "Employee ID" << setw(15) << "Hours" << setw(15) << "Payrate" << setw(15) << "Grosspay" << endl << fixed << showpoint;

    while (inClientFile >> id >> hours >> payrate)

        outputLine(id, hours, payrate, grosspay = hours * payrate);
}
void outputLine(int id, float hours, float payrate, float grosspay)
{
    cout << left << setw(7) << id << setprecision(2) << setw(8) << " , " << setw(8) << hours << setprecision(2) << setw(7) 
        << " , " << "$"  << setw(7) << payrate << setprecision(2) << setw(7) << " , " << "$"  << grosspay << right << endl;
}

测试文件

#include "File.h"

int main()
{
    File myFile;
    myFile.Create();
    myFile.Read();
}

1 个答案:

答案 0 :(得分:1)

你不应该使用例外,除非在&#34;例外&#34;程序无法轻松恢复的情况(如内存分配错误,打开文件时出错等)。使用while循环可以更自然地完成验证输入,如下所示:

while( ! (std::cin >> id >> hours >> payrate) ) // repeat until we read correctly
{
    std::cout << "Invalid input, try again..." << std::endl;
    std::cin.clear(); // clear the error flags
    // ignore the rest of the stream, must #include <limits>
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
}
// now we can write the result to the file, input was validated
outClientFile << id << ' ' << hours << ' ' << payrate << endl;

如果cin正确读取,则会转换为bool true,并且不会执行循环。如果不是(即一些非数字输入),则cin >> ...的最终结果将是转换为false的流。在后一种情况下,您需要清除错误标志(std::cin.clear()部分),然后删除流中剩余的其余字符(std::cin.ignore()部分)并重复。